mobileapplicationPassvault/node_modules/firebase/firebase-compat.js.map

1 line
5.6 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-compat.js","sources":["../util/src/constants.ts","../util/src/assert.ts","../util/src/crypt.ts","../util/src/deepCopy.ts","../util/src/global.ts","../util/src/defaults.ts","../logger/src/logger.ts","../../node_modules/idb/build/index.js","../util/src/deferred.ts","../util/src/emulator.ts","../util/src/environment.ts","../util/src/errors.ts","../util/src/json.ts","../util/src/jwt.ts","../util/src/obj.ts","../util/src/query.ts","../util/src/sha1.ts","../util/src/subscribe.ts","../util/src/validation.ts","../util/src/uuid.ts","../util/src/utf8.ts","../util/src/exponential_backoff.ts","../util/src/compat.ts","../component/src/component.ts","../component/src/constants.ts","../component/src/provider.ts","../component/src/component_container.ts","../../node_modules/idb/build/wrap-idb-value.js","../app/src/platformLoggerService.ts","../app/src/logger.ts","../app/src/registerCoreComponents.ts","../app/src/constants.ts","../app/src/internal.ts","../app/src/errors.ts","../app/src/firebaseApp.ts","../app/src/api.ts","../app/src/indexeddb.ts","../app/src/heartbeatService.ts","../app/src/index.ts","../app-compat/src/firebaseApp.ts","../app-compat/src/errors.ts","../app-compat/src/firebaseNamespaceCore.ts","../app-compat/src/firebaseNamespace.ts","../app-compat/src/logger.ts","../app-compat/src/index.ts","../app-compat/src/registerCoreComponents.ts","compat/app/index.ts","../installations/src/util/constants.ts","../installations/src/util/errors.ts","../installations/src/functions/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/helpers/get-installation-entry.ts","../installations/src/functions/create-installation-request.ts","../installations/src/functions/generate-auth-token-request.ts","../installations/src/helpers/refresh-auth-token.ts","../installations/src/api/get-token.ts","../installations/src/helpers/extract-app-config.ts","../installations/src/functions/config.ts","../installations/src/api/get-id.ts","../installations/src/index.ts","../analytics/src/constants.ts","../analytics/src/logger.ts","../analytics/src/errors.ts","../analytics/src/helpers.ts","../analytics/src/get-config.ts","../analytics/src/initialize-analytics.ts","../analytics/src/factory.ts","../analytics/src/api.ts","../analytics/src/functions.ts","../analytics/src/index.ts","../analytics-compat/src/constants.ts","../analytics-compat/src/index.ts","../analytics-compat/src/service.ts","../app-check/src/state.ts","../app-check/src/constants.ts","../app-check/src/proactive-refresh.ts","../app-check/src/errors.ts","../app-check/src/util.ts","../app-check/src/client.ts","../app-check/src/indexeddb.ts","../app-check/src/logger.ts","../app-check/src/storage.ts","../app-check/src/debug.ts","../app-check/src/internal-api.ts","../app-check/src/factory.ts","../app-check/src/recaptcha.ts","../app-check/src/providers.ts","../app-check/src/api.ts","../app-check/src/index.ts","../app-check-compat/src/errors.ts","../app-check-compat/src/service.ts","../app-check-compat/src/index.ts","../../node_modules/tslib/tslib.es6.js","../auth/src/model/enum_maps.ts","../auth/src/core/errors.ts","../auth/src/core/util/log.ts","../auth/src/core/util/assert.ts","../auth/src/core/util/location.ts","../auth/src/core/util/delay.ts","../auth/src/core/util/navigator.ts","../auth/src/core/util/emulator.ts","../auth/src/core/util/fetch_provider.ts","../auth/src/api/errors.ts","../auth/src/api/index.ts","../auth/src/platform_browser/recaptcha/recaptcha.ts","../auth/src/core/util/time.ts","../auth/src/core/user/id_token_result.ts","../auth/src/core/user/invalidation.ts","../auth/src/core/user/proactive_refresh.ts","../auth/src/core/user/user_metadata.ts","../auth/src/core/user/reload.ts","../auth/src/api/account_management/account.ts","../auth/src/core/user/token_manager.ts","../auth/src/api/authentication/token.ts","../auth/src/core/user/user_impl.ts","../auth/src/core/util/instantiator.ts","../auth/src/core/persistence/in_memory.ts","../auth/src/core/persistence/persistence_user_manager.ts","../auth/src/core/util/browser.ts","../auth/src/core/util/version.ts","../auth/src/core/auth/middleware.ts","../auth/src/core/auth/password_policy_impl.ts","../auth/src/core/auth/auth_impl.ts","../auth/src/api/password_policy/get_password_policy.ts","../auth/src/platform_browser/load_js.ts","../auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts","../auth/src/api/authentication/recaptcha.ts","../auth/src/core/auth/emulator.ts","../auth/src/core/credentials/auth_credential.ts","../auth/src/api/account_management/email_and_password.ts","../auth/src/api/authentication/email_and_password.ts","../auth/src/core/credentials/email.ts","../auth/src/api/authentication/email_link.ts","../auth/src/api/authentication/idp.ts","../auth/src/core/credentials/oauth.ts","../auth/src/api/authentication/sms.ts","../auth/src/core/credentials/phone.ts","../auth/src/core/action_code_url.ts","../auth/src/core/providers/email.ts","../auth/src/core/providers/federated.ts","../auth/src/core/providers/oauth.ts","../auth/src/core/providers/facebook.ts","../auth/src/core/providers/google.ts","../auth/src/core/providers/github.ts","../auth/src/core/credentials/saml.ts","../auth/src/core/providers/saml.ts","../auth/src/core/providers/twitter.ts","../auth/src/api/authentication/sign_up.ts","../auth/src/core/user/user_credential_impl.ts","../auth/src/mfa/mfa_error.ts","../auth/src/core/util/providers.ts","../auth/src/core/user/link_unlink.ts","../auth/src/core/user/reauthenticate.ts","../auth/src/core/strategies/credential.ts","../auth/src/core/strategies/custom_token.ts","../auth/src/api/authentication/custom_token.ts","../auth/src/mfa/mfa_info.ts","../auth/src/core/strategies/action_code_settings.ts","../auth/src/core/strategies/email_and_password.ts","../auth/src/core/strategies/email.ts","../auth/src/api/authentication/create_auth_uri.ts","../auth/src/core/user/account_info.ts","../auth/src/api/account_management/profile.ts","../auth/src/core/user/additional_user_info.ts","../auth/src/mfa/mfa_session.ts","../auth/src/mfa/mfa_resolver.ts","../auth/src/mfa/mfa_user.ts","../auth/src/api/account_management/mfa.ts","../auth/src/core/persistence/index.ts","../auth/src/platform_browser/persistence/browser.ts","../auth/src/platform_browser/persistence/local_storage.ts","../auth/src/platform_browser/persistence/session_storage.ts","../auth/src/platform_browser/messagechannel/receiver.ts","../auth/src/platform_browser/messagechannel/promise.ts","../auth/src/core/util/event_id.ts","../auth/src/platform_browser/messagechannel/sender.ts","../auth/src/platform_browser/auth_window.ts","../auth/src/platform_browser/util/worker.ts","../auth/src/platform_browser/persistence/indexed_db.ts","../auth/src/platform_browser/recaptcha/recaptcha_mock.ts","../auth/src/platform_browser/recaptcha/recaptcha_loader.ts","../auth/src/platform_browser/recaptcha/recaptcha_verifier.ts","../auth/src/platform_browser/strategies/phone.ts","../auth/src/api/authentication/mfa.ts","../auth/src/platform_browser/providers/phone.ts","../auth/src/core/util/resolver.ts","../auth/src/core/strategies/idp.ts","../auth/src/core/strategies/abstract_popup_redirect_operation.ts","../auth/src/platform_browser/strategies/popup.ts","../auth/src/core/strategies/redirect.ts","../auth/src/platform_browser/strategies/redirect.ts","../auth/src/core/auth/auth_event_manager.ts","../auth/src/api/project_config/get_project_config.ts","../auth/src/core/util/validate_origin.ts","../auth/src/platform_browser/iframe/gapi.ts","../auth/src/platform_browser/iframe/iframe.ts","../auth/src/platform_browser/util/popup.ts","../auth/src/core/util/handler.ts","../auth/src/platform_browser/popup_redirect.ts","../auth/src/platform_browser/mfa/assertions/phone.ts","../auth/src/mfa/mfa_assertion.ts","../auth/src/core/auth/firebase_internal.ts","../auth/src/platform_browser/index.ts","../auth/src/core/auth/register.ts","../auth/src/platform_cordova/plugins.ts","../auth/src/core/auth/initialize.ts","../auth/src/platform_cordova/popup_redirect/utils.ts","../auth/src/platform_cordova/popup_redirect/events.ts","../auth/src/platform_cordova/popup_redirect/popup_redirect.ts","../auth-compat/index.ts","../auth-compat/src/platform.ts","../auth-compat/src/persistence.ts","../auth-compat/src/popup_redirect.ts","../auth-compat/src/wrap.ts","../auth-compat/src/user_credential.ts","../auth-compat/src/user.ts","../auth-compat/src/auth.ts","../auth/src/core/strategies/email_link.ts","../auth/internal/index.ts","../auth/src/core/strategies/anonymous.ts","../auth-compat/src/phone_auth_provider.ts","../auth-compat/src/recaptcha_verifier.ts","../database/src/core/version.ts","../database/src/core/storage/DOMStorageWrapper.ts","../database/src/core/storage/MemoryStorage.ts","../database/src/core/storage/storage.ts","../database/src/core/snap/snap.ts","../database/src/core/snap/indexes/PriorityIndex.ts","../database/src/core/operation/Operation.ts","../database/src/core/SyncPoint.ts","../database/src/core/SyncTree.ts","../database/src/register.ts","../database/src/core/util/util.ts","../database/src/core/AppCheckTokenProvider.ts","../database/src/core/AuthTokenProvider.ts","../database/src/realtime/Constants.ts","../database/src/core/RepoInfo.ts","../database/src/core/stats/StatsCollection.ts","../database/src/core/stats/StatsManager.ts","../database/src/realtime/polling/PacketReceiver.ts","../database/src/realtime/BrowserPollConnection.ts","../database/src/realtime/WebSocketConnection.ts","../database/src/realtime/TransportManager.ts","../database/src/realtime/Connection.ts","../database/src/core/ServerActions.ts","../database/src/core/util/EventEmitter.ts","../database/src/core/util/OnlineMonitor.ts","../database/src/core/util/Path.ts","../database/src/core/util/VisibilityMonitor.ts","../database/src/core/PersistentConnection.ts","../database/src/core/snap/Node.ts","../database/src/core/snap/indexes/Index.ts","../database/src/core/snap/indexes/KeyIndex.ts","../database/src/core/util/SortedMap.ts","../database/src/core/snap/comparators.ts","../database/src/core/snap/LeafNode.ts","../database/src/core/snap/childSet.ts","../database/src/core/snap/IndexMap.ts","../database/src/core/snap/ChildrenNode.ts","../database/src/core/snap/nodeFromJSON.ts","../database/src/core/snap/indexes/PathIndex.ts","../database/src/core/snap/indexes/ValueIndex.ts","../database/src/core/view/Change.ts","../database/src/core/view/filter/IndexedFilter.ts","../database/src/core/view/filter/RangedFilter.ts","../database/src/core/view/filter/LimitedFilter.ts","../database/src/core/view/QueryParams.ts","../database/src/core/ReadonlyRestClient.ts","../database/src/core/SnapshotHolder.ts","../database/src/core/SparseSnapshotTree.ts","../database/src/core/stats/StatsListener.ts","../database/src/core/stats/StatsReporter.ts","../database/src/core/operation/AckUserWrite.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/EventGenerator.ts","../database/src/core/view/ViewCache.ts","../database/src/core/util/ImmutableTree.ts","../database/src/core/CompoundWrite.ts","../database/src/core/WriteTree.ts","../database/src/core/view/ChildChangeAccumulator.ts","../database/src/core/view/CompleteChildSource.ts","../database/src/core/view/ViewProcessor.ts","../database/src/core/view/View.ts","../database/src/core/util/ServerValues.ts","../database/src/core/util/Tree.ts","../database/src/core/util/validation.ts","../database/src/core/view/EventQueue.ts","../database/src/core/Repo.ts","../database/src/core/util/libs/parser.ts","../database/src/core/util/NextPushId.ts","../database/src/core/view/Event.ts","../database/src/core/view/EventRegistration.ts","../database/src/api/OnDisconnect.ts","../database/src/api/Reference_impl.ts","../database/src/api/Database.ts","../database/src/api/ServerValue.ts","../database/src/api/Transaction.ts","../database/src/api/test_access.ts","../database-compat/src/util/util.ts","../database-compat/src/api/onDisconnect.ts","../database-compat/src/api/TransactionResult.ts","../database-compat/src/api/Reference.ts","../database-compat/src/util/validation.ts","../database-compat/src/api/Database.ts","../database-compat/src/index.ts","../database-compat/src/api/internal.ts","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/base.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/disposable.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/array/array.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/event.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserfeature.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/internal.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/util.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/reflect/reflect.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/useragent/useragent.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/browser.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/engine.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserevent.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtype.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenable.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenablekey.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listener.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenermap.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/object/object.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/events.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtarget.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/json.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/workqueue.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/freelist.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/run.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throwexception.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/timer/timer.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throttle.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventhandler.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchanneldebug.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/requeststats.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/errorcode.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/eventtype.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttpfactory.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttp.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/channelrequest.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/environment.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbase.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/uri.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/dispose.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wirev8.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xhrio.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/structs/structs.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/string.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/utils.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wire.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/nativejsonprocessor.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/functions/functions.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/netutils.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/fetchxmlhttpfactory.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/hybrid.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/httpstatus.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/rpc/httpcors.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbasetransport.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/crypt/md5.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/crypt/hash.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/math/integer.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransport.js","../webchannel-wrapper/dist/temp/src/index.js","../firestore/src/remote/rpc_error.ts","../firestore/src/auth/user.ts","../firestore/src/core/version.ts","../firestore/src/util/log.ts","../firestore/src/platform/browser/format_json.ts","../firestore/src/util/assert.ts","../firestore/src/util/error.ts","../firestore/src/util/promise.ts","../firestore/src/api/credentials.ts","../firestore/src/util/misc.ts","../firestore/src/platform/browser/random_bytes.ts","../firestore/src/lite-api/timestamp.ts","../firestore/src/core/snapshot_version.ts","../firestore/src/model/path.ts","../firestore/src/model/document_key.ts","../firestore/src/model/field_index.ts","../firestore/src/local/persistence_transaction.ts","../firestore/src/local/local_store.ts","../firestore/src/local/persistence_promise.ts","../firestore/src/local/simple_db.ts","../firestore/src/local/index_backfiller.ts","../firestore/src/core/listen_sequence.ts","../firestore/src/util/types.ts","../firestore/src/local/encoded_resource_path.ts","../firestore/src/local/indexeddb_sentinels.ts","../firestore/src/local/indexeddb_schema_legacy.ts","../firestore/src/local/indexeddb_transaction.ts","../firestore/src/util/obj.ts","../firestore/src/util/sorted_map.ts","../firestore/src/util/sorted_set.ts","../firestore/src/model/field_mask.ts","../firestore/src/util/base64_decode_error.ts","../firestore/src/util/byte_string.ts","../firestore/src/platform/browser/base64.ts","../firestore/src/model/normalize.ts","../firestore/src/model/server_timestamps.ts","../firestore/src/core/database_info.ts","../firestore/src/model/values.ts","../firestore/src/model/object_value.ts","../firestore/src/model/document.ts","../firestore/src/core/bound.ts","../firestore/src/core/order_by.ts","../firestore/src/core/filter.ts","../firestore/src/core/target.ts","../firestore/src/core/query.ts","../firestore/src/util/obj_map.ts","../firestore/src/model/collections.ts","../firestore/src/remote/number_serializer.ts","../firestore/src/model/transform_operation.ts","../firestore/src/model/mutation.ts","../firestore/src/model/mutation_batch.ts","../firestore/src/model/overlay.ts","../firestore/src/remote/existence_filter.ts","../firestore/src/platform/browser/text_serializer.ts","../firestore/src/remote/bloom_filter.ts","../firestore/src/remote/remote_event.ts","../firestore/src/remote/watch_change.ts","../firestore/src/remote/serializer.ts","../firestore/src/local/target_data.ts","../firestore/src/local/local_serializer.ts","../firestore/src/local/indexeddb_bundle_cache.ts","../firestore/src/local/indexeddb_document_overlay_cache.ts","../firestore/src/index/firestore_index_value_writer.ts","../firestore/src/index/ordered_code_writer.ts","../firestore/src/index/index_byte_encoder.ts","../firestore/src/index/index_entry.ts","../firestore/src/model/target_index_matcher.ts","../firestore/src/util/logic_utils.ts","../firestore/src/local/memory_index_manager.ts","../firestore/src/local/indexeddb_index_manager.ts","../firestore/src/local/lru_garbage_collector.ts","../firestore/src/local/indexeddb_mutation_batch_impl.ts","../firestore/src/local/indexeddb_mutation_queue.ts","../firestore/src/core/target_id_generator.ts","../firestore/src/local/indexeddb_target_cache.ts","../firestore/src/local/lru_garbage_collector_impl.ts","../firestore/src/local/indexeddb_lru_delegate_impl.ts","../firestore/src/local/remote_document_change_buffer.ts","../firestore/src/local/indexeddb_remote_document_cache.ts","../firestore/src/local/overlayed_document.ts","../firestore/src/local/local_documents_view.ts","../firestore/src/local/memory_bundle_cache.ts","../firestore/src/local/memory_document_overlay_cache.ts","../firestore/src/local/reference_set.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/local/indexeddb_schema_converter.ts","../firestore/src/local/indexeddb_persistence.ts","../firestore/src/local/indexeddb_schema.ts","../firestore/src/local/local_view_changes.ts","../firestore/src/local/query_context.ts","../firestore/src/local/query_engine.ts","../firestore/src/local/local_store_impl.ts","../firestore/src/local/shared_client_state_schema.ts","../firestore/src/local/shared_client_state.ts","../firestore/src/remote/connectivity_monitor_noop.ts","../firestore/src/platform/browser/connectivity_monitor.ts","../firestore/src/util/debug_uid.ts","../firestore/src/remote/rest_connection.ts","../firestore/src/remote/stream_bridge.ts","../firestore/src/platform/browser/webchannel_connection.ts","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransportfactory.js","../firestore/src/platform/browser/dom.ts","../firestore/src/platform/browser/serializer.ts","../firestore/src/remote/backoff.ts","../firestore/src/remote/persistent_stream.ts","../firestore/src/remote/datastore.ts","../firestore/src/remote/online_state_tracker.ts","../firestore/src/remote/remote_store.ts","../firestore/src/util/async_queue.ts","../firestore/src/model/document_set.ts","../firestore/src/core/view_snapshot.ts","../firestore/src/core/event_manager.ts","../firestore/src/util/bundle_reader.ts","../firestore/src/core/bundle_impl.ts","../firestore/src/core/view.ts","../firestore/src/core/sync_engine_impl.ts","../firestore/src/core/component_provider.ts","../firestore/src/platform/browser/connection.ts","../firestore/src/util/byte_stream.ts","../firestore/src/util/async_observer.ts","../firestore/src/util/bundle_reader_impl.ts","../firestore/src/core/transaction.ts","../firestore/src/core/transaction_runner.ts","../firestore/src/core/firestore_client.ts","../firestore/src/platform/browser/byte_stream_reader.ts","../firestore/src/api/long_polling_options.ts","../firestore/src/lite-api/components.ts","../firestore/src/util/input_validation.ts","../firestore/src/lite-api/settings.ts","../firestore/src/lite-api/database.ts","../firestore/src/lite-api/reference.ts","../firestore/src/util/async_queue_impl.ts","../firestore/src/api/observer.ts","../firestore/src/api/bundle.ts","../firestore/src/api/database.ts","../firestore/src/register.ts","../firestore-compat/src/index.ts","../firestore-compat/src/config.ts","../functions/src/config.ts","../firestore/src/lite-api/bytes.ts","../firestore/src/lite-api/field_path.ts","../firestore/src/lite-api/field_value.ts","../firestore/src/lite-api/geo_point.ts","../firestore/src/lite-api/user_data_reader.ts","../firestore/src/lite-api/snapshot.ts","../firestore/src/lite-api/query.ts","../firestore/src/lite-api/user_data_writer.ts","../firestore/src/lite-api/reference_impl.ts","../firestore/src/api/snapshot.ts","../firestore/src/api/reference_impl.ts","../firestore/src/core/transaction_options.ts","../firestore/src/lite-api/write_batch.ts","../firestore/src/api/transaction.ts","../firestore/src/lite-api/transaction.ts","../firestore-compat/src/util/input_validation.ts","../firestore-compat/src/api/blob.ts","../firestore-compat/src/api/observer.ts","../firestore-compat/src/api/database.ts","../firestore-compat/src/api/field_path.ts","../firestore-compat/src/api/field_value.ts","../firestore/src/lite-api/field_value_impl.ts","../functions/src/serializer.ts","../functions/src/constants.ts","../functions/src/error.ts","../functions/src/context.ts","../functions/src/service.ts","../functions/src/api.ts","../functions/src/index.ts","../functions-compat/src/register.ts","../messaging/src/util/constants.ts","../messaging/src/interfaces/internal-message-payload.ts","../functions-compat/src/service.ts","../functions-compat/src/index.ts","../messaging/src/helpers/array-base64-translator.ts","../messaging/src/helpers/migrate-old-database.ts","../messaging/src/internals/idb-manager.ts","../messaging/src/util/errors.ts","../messaging/src/internals/requests.ts","../messaging/src/internals/token-manager.ts","../messaging/src/helpers/externalizePayload.ts","../messaging/src/helpers/logToFirelog.ts","../messaging/src/helpers/extract-app-config.ts","../messaging/src/messaging-service.ts","../messaging/src/helpers/registerDefaultSw.ts","../messaging/src/api/getToken.ts","../messaging/src/helpers/updateVapidKey.ts","../messaging/src/helpers/updateSwReg.ts","../messaging/src/helpers/logToScion.ts","../messaging/src/listeners/window-listener.ts","../messaging/src/helpers/is-console-message.ts","../messaging/src/helpers/register.ts","../messaging/src/api.ts","../messaging/src/api/deleteToken.ts","../messaging/src/api/onMessage.ts","../messaging/src/listeners/sw-listeners.ts","../messaging/src/helpers/sleep.ts","../messaging/src/api/onBackgroundMessage.ts","../storage/src/implementation/error.ts","../storage/src/implementation/connection.ts","../storage-compat/src/index.ts","../messaging-compat/src/messaging-compat.ts","../messaging-compat/src/registerMessagingCompat.ts","../messaging-compat/src/index.ts","../storage/src/implementation/constants.ts","../storage/src/implementation/location.ts","../storage/src/implementation/failrequest.ts","../storage/src/implementation/type.ts","../storage/src/implementation/url.ts","../storage/src/implementation/utils.ts","../storage/src/implementation/request.ts","../storage/src/implementation/backoff.ts","../storage/src/implementation/fs.ts","../storage/src/platform/browser/base64.ts","../storage/src/implementation/string.ts","../storage/src/implementation/blob.ts","../storage/src/implementation/json.ts","../storage/src/implementation/path.ts","../storage/src/implementation/metadata.ts","../storage/src/implementation/list.ts","../storage/src/implementation/requestinfo.ts","../storage/src/implementation/requests.ts","../storage/src/implementation/taskenums.ts","../storage/src/implementation/observer.ts","../storage/src/implementation/async.ts","../storage/src/platform/browser/connection.ts","../storage/src/task.ts","../storage/src/reference.ts","../storage/src/service.ts","../storage/src/api.ts","../storage/src/index.ts","../storage/src/constants.ts","../storage-compat/src/tasksnapshot.ts","../storage-compat/src/task.ts","../storage-compat/src/list.ts","../storage-compat/src/reference.ts","../storage-compat/src/service.ts","../performance/src/constants.ts","../performance/src/utils/attributes_utils.ts","../performance-compat/src/index.ts","../remote-config-compat/src/index.ts","../performance/src/utils/errors.ts","../performance/src/utils/console_logger.ts","../performance/src/services/api_service.ts","../performance/src/services/iid_service.ts","../performance/src/utils/string_merger.ts","../performance/src/services/settings_service.ts","../performance/src/utils/app_utils.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/src/index.ts","../performance-compat/src/performance.ts","../remote-config/src/client/remote_config_fetch_client.ts","../remote-config/src/constants.ts","../remote-config/src/errors.ts","../remote-config/src/value.ts","../remote-config/src/api.ts","../remote-config/src/client/caching_client.ts","../remote-config/src/client/rest_client.ts","../remote-config/src/language.ts","../remote-config/src/client/retrying_client.ts","../remote-config/src/remote_config.ts","../remote-config/src/storage/storage.ts","../remote-config/src/storage/storage_cache.ts","../remote-config/src/api2.ts","../remote-config/src/register.ts","../remote-config-compat/src/remoteConfig.ts","compat/index.cdn.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 new DecodeBase64StringError();\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 * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\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 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 *\n * Note: we don't merge __proto__ to prevent prototype pollution\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 // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\n continue;\n }\n (target as Record<string, unknown>)[prop] = deepExtend(\n (target as Record<string, unknown>)[prop],\n (source as Record<string, unknown>)[prop]\n );\n }\n\n return target;\n}\n\nfunction isValidKey(key: string): boolean {\n return key !== '__proto__';\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record<string, string>;\n emulatorHosts?: Record<string, string>;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record<string, string> | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = <T extends ExperimentalKey>(\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial<FirebaseIdToken>;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\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 or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\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/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n !!navigator.userAgent &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise<boolean> {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @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 as FirebaseError)?.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]: unknown;\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 /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\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, customData);\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 ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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/**\n * Deep equal two objects. Support Arrays and Objects.\n */\nexport function deepEqual(a: object, b: object): boolean {\n if (a === b) {\n return true;\n }\n\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n for (const k of aKeys) {\n if (!bKeys.includes(k)) {\n return false;\n }\n\n const aProp = (a as Record<string, unknown>)[k];\n const bProp = (b as Record<string, unknown>)[k];\n if (isObject(aProp) && isObject(bProp)) {\n if (!deepEqual(aProp, bProp)) {\n return false;\n }\n } else if (aProp !== bProp) {\n return false;\n }\n }\n\n for (const k of bKeys) {\n if (!aKeys.includes(k)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isObject(thing: unknown): thing is object {\n return thing !== null && typeof thing === 'object';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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): Record<string, string> {\n const obj: Record<string, string> = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const [key, value] = token.split('=');\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n });\n return obj;\n}\n\n/**\n * Extract the query string part of a URL, including the leading question mark (if present).\n */\nexport function extractQuerystring(url: string): string {\n const queryStart = url.indexOf('?');\n if (!queryStart) {\n return '';\n }\n const fragmentStart = url.indexOf('#', queryStart);\n return url.substring(\n queryStart,\n fragmentStart > 0 ? fragmentStart : undefined\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\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?: NextFn<T> | PartialObserver<T>,\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. */\n// eslint-disable-next-line @typescript-eslint/ban-types\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 argName The name of the argument\n * @return The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(fnName: string, argName: string): string {\n return `${fnName} failed: ${argName} argument `;\n}\n\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nexport function validateNamespace(\n fnName: string,\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, 'namespace') + 'must be a valid firebase namespace.'\n );\n }\n}\n\nexport function validateCallback(\n fnName: string,\n argumentName: string,\n // eslint-disable-next-line @typescript-eslint/ban-types\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, argumentName) + 'must be a valid function.'\n );\n }\n}\n\nexport function validateContextObject(\n fnName: string,\n argumentName: string,\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, argumentName) + 'must be a valid context object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Copied from https://stackoverflow.com/a/2117523\n * Generates a new uuid.\n * @public\n */\nexport const uuidv4 = function (): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = (Math.random() * 16) | 0,\n v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_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(\n backoffCount: number,\n intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): 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 = intervalMillis * Math.pow(backoffFactor, 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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n service: Compat<ExpService> | ExpService\n): ExpService {\n if (service && (service as Compat<ExpService>)._delegate) {\n return (service as Compat<ExpService>)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\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 onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\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 setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\nimport { ComponentContainer } from './component_container';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport {\n InitializeOptions,\n InstantiationMode,\n Name,\n NameServiceMapping,\n OnInitCallBack\n} 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 private readonly instancesOptions: Map<string, Record<string, unknown>> =\n new Map();\n private onInitCallbacks: Map<string, Set<OnInitCallBack<T>>> = 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): 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\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n // initialize the service if it can be auto-initialized\n try {\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\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\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 // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n options?.identifier\n );\n const optional = options?.optional ?? false;\n\n if (\n this.isInitialized(normalizedIdentifier) ||\n this.shouldAutoInitialize()\n ) {\n try {\n return this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier\n });\n } catch (e) {\n if (optional) {\n return null;\n } else {\n throw e;\n }\n }\n } else {\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\n if (optional) {\n return null;\n } else {\n throw Error(`Service ${this.name} is not available`);\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\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\n if (!this.shouldAutoInitialize()) {\n return;\n }\n\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService({ instanceIdentifier: 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 =\n this.normalizeInstanceIdentifier(instanceIdentifier);\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({\n instanceIdentifier: normalizedIdentifier\n })!;\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.instancesOptions.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) // legacy services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any).INTERNAL!.delete()),\n ...services\n .filter(service => '_delete' in service) // modularized services\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any)._delete())\n ]);\n }\n\n isComponentSet(): boolean {\n return this.component != null;\n }\n\n isInitialized(identifier: string = DEFAULT_ENTRY_NAME): boolean {\n return this.instances.has(identifier);\n }\n\n getOptions(identifier: string = DEFAULT_ENTRY_NAME): Record<string, unknown> {\n return this.instancesOptions.get(identifier) || {};\n }\n\n initialize(opts: InitializeOptions = {}): NameServiceMapping[T] {\n const { options = {} } = opts;\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n opts.instanceIdentifier\n );\n if (this.isInitialized(normalizedIdentifier)) {\n throw Error(\n `${this.name}(${normalizedIdentifier}) has already been initialized`\n );\n }\n\n if (!this.isComponentSet()) {\n throw Error(`Component ${this.name} has not been registered yet`);\n }\n\n const instance = this.getOrInitializeService({\n instanceIdentifier: normalizedIdentifier,\n options\n })!;\n\n // resolve any pending promise waiting for the service instance\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedDeferredIdentifier =\n this.normalizeInstanceIdentifier(instanceIdentifier);\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\n instanceDeferred.resolve(instance);\n }\n }\n\n return instance;\n }\n\n /**\n *\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\n *\n * @param identifier An optional instance identifier\n * @returns a function to unregister the callback\n */\n onInit(callback: OnInitCallBack<T>, identifier?: string): () => void {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n const existingCallbacks =\n this.onInitCallbacks.get(normalizedIdentifier) ??\n new Set<OnInitCallBack<T>>();\n existingCallbacks.add(callback);\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\n\n const existingInstance = this.instances.get(normalizedIdentifier);\n if (existingInstance) {\n callback(existingInstance, normalizedIdentifier);\n }\n\n return () => {\n existingCallbacks.delete(callback);\n };\n }\n\n /**\n * Invoke onInit callbacks synchronously\n * @param instance the service instance`\n */\n private invokeOnInitCallbacks(\n instance: NameServiceMapping[T],\n identifier: string\n ): void {\n const callbacks = this.onInitCallbacks.get(identifier);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n try {\n callback(instance, identifier);\n } catch {\n // ignore errors in the onInit callback\n }\n }\n }\n\n private getOrInitializeService({\n instanceIdentifier,\n options = {}\n }: {\n instanceIdentifier: string;\n options?: Record<string, unknown>;\n }): NameServiceMapping[T] | null {\n let instance = this.instances.get(instanceIdentifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(this.container, {\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\n options\n });\n this.instances.set(instanceIdentifier, instance);\n this.instancesOptions.set(instanceIdentifier, options);\n\n /**\n * Invoke onInit listeners.\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\n * while onInit listeners are registered by consumers of the provider.\n */\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\n\n /**\n * Order is important\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\n * makes `isInitialized()` return true.\n */\n if (this.component.onInstanceCreated) {\n try {\n this.component.onInstanceCreated(\n this.container,\n instanceIdentifier,\n instance\n );\n } catch {\n // ignore errors in the onInstanceCreatedCallback\n }\n }\n }\n\n return instance || null;\n }\n\n private normalizeInstanceIdentifier(\n identifier: string = DEFAULT_ENTRY_NAME\n ): 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 private shouldAutoInitialize(): boolean {\n return (\n !!this.component &&\n this.component.instantiationMode !== InstantiationMode.EXPLICIT\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<T extends Name>(component: Component<T>): boolean {\n return component.instantiationMode === InstantiationMode.EAGER;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 unknown 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 as unknown as Provider<Name>);\n\n return provider as Provider<T>;\n }\n\n getProviders(): Array<Provider<Name>> {\n return Array.from(this.providers.values());\n }\n}\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ComponentContainer,\n ComponentType,\n Provider,\n Name\n} from '@firebase/component';\nimport { PlatformLoggerService, VersionService } from './types';\n\nexport class PlatformLoggerServiceImpl implements 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() as VersionService;\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(provider: Provider<Name>): boolean {\n const component = provider.getComponent();\n return component?.type === ComponentType.VERSION;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Component, ComponentType } from '@firebase/component';\nimport { PlatformLoggerServiceImpl } from './platformLoggerService';\nimport { name, version } from '../package.json';\nimport { _registerComponent } from './internal';\nimport { registerVersion } from './api';\nimport { HeartbeatServiceImpl } from './heartbeatService';\n\nexport function registerCoreComponents(variant?: string): void {\n _registerComponent(\n new Component(\n 'platform-logger',\n container => new PlatformLoggerServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n _registerComponent(\n new Component(\n 'heartbeat',\n container => new HeartbeatServiceImpl(container),\n ComponentType.PRIVATE\n )\n );\n\n // Register `app` package.\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n // Register platform SDK identifier (no version).\n registerVersion('fire-js', '');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { name as appName } from '../package.json';\nimport { name as appCompatName } from '../../app-compat/package.json';\nimport { name as analyticsCompatName } from '../../../packages/analytics-compat/package.json';\nimport { name as analyticsName } from '../../../packages/analytics/package.json';\nimport { name as appCheckCompatName } from '../../../packages/app-check-compat/package.json';\nimport { name as appCheckName } from '../../../packages/app-check/package.json';\nimport { name as authName } from '../../../packages/auth/package.json';\nimport { name as authCompatName } from '../../../packages/auth-compat/package.json';\nimport { name as databaseName } from '../../../packages/database/package.json';\nimport { name as databaseCompatName } from '../../../packages/database-compat/package.json';\nimport { name as functionsName } from '../../../packages/functions/package.json';\nimport { name as functionsCompatName } from '../../../packages/functions-compat/package.json';\nimport { name as installationsName } from '../../../packages/installations/package.json';\nimport { name as installationsCompatName } from '../../../packages/installations-compat/package.json';\nimport { name as messagingName } from '../../../packages/messaging/package.json';\nimport { name as messagingCompatName } from '../../../packages/messaging-compat/package.json';\nimport { name as performanceName } from '../../../packages/performance/package.json';\nimport { name as performanceCompatName } from '../../../packages/performance-compat/package.json';\nimport { name as remoteConfigName } from '../../../packages/remote-config/package.json';\nimport { name as remoteConfigCompatName } from '../../../packages/remote-config-compat/package.json';\nimport { name as storageName } from '../../../packages/storage/package.json';\nimport { name as storageCompatName } from '../../../packages/storage-compat/package.json';\nimport { name as firestoreName } from '../../../packages/firestore/package.json';\nimport { name as firestoreCompatName } from '../../../packages/firestore-compat/package.json';\nimport { name as packageName } from '../../../packages/firebase/package.json';\n\n/**\n * The default app name\n *\n * @internal\n */\nexport const DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\nexport const PLATFORM_LOG_STRING = {\n [appName]: 'fire-core',\n [appCompatName]: 'fire-core-compat',\n [analyticsName]: 'fire-analytics',\n [analyticsCompatName]: 'fire-analytics-compat',\n [appCheckName]: 'fire-app-check',\n [appCheckCompatName]: 'fire-app-check-compat',\n [authName]: 'fire-auth',\n [authCompatName]: 'fire-auth-compat',\n [databaseName]: 'fire-rtdb',\n [databaseCompatName]: 'fire-rtdb-compat',\n [functionsName]: 'fire-fn',\n [functionsCompatName]: 'fire-fn-compat',\n [installationsName]: 'fire-iid',\n [installationsCompatName]: 'fire-iid-compat',\n [messagingName]: 'fire-fcm',\n [messagingCompatName]: 'fire-fcm-compat',\n [performanceName]: 'fire-perf',\n [performanceCompatName]: 'fire-perf-compat',\n [remoteConfigName]: 'fire-rc',\n [remoteConfigCompatName]: 'fire-rc-compat',\n [storageName]: 'fire-gcs',\n [storageCompatName]: 'fire-gcs-compat',\n [firestoreName]: 'fire-fst',\n [firestoreCompatName]: 'fire-fst-compat',\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from './public-types';\nimport { Component, Provider, Name } from '@firebase/component';\nimport { logger } from './logger';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { FirebaseAppImpl } from './firebaseApp';\n\n/**\n * @internal\n */\nexport const _apps = new Map<string, FirebaseApp>();\n\n/**\n * Registered components.\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const _components = new Map<string, Component<any>>();\n\n/**\n * @param component - the component being added to this app's container\n *\n * @internal\n */\nexport function _addComponent<T extends Name>(\n app: FirebaseApp,\n component: Component<T>\n): void {\n try {\n (app as FirebaseAppImpl).container.addComponent(component);\n } catch (e) {\n logger.debug(\n `Component ${component.name} failed to register with FirebaseApp ${app.name}`,\n e\n );\n }\n}\n\n/**\n *\n * @internal\n */\nexport function _addOrOverwriteComponent(\n app: FirebaseApp,\n component: Component\n): void {\n (app as FirebaseAppImpl).container.addOrOverwriteComponent(component);\n}\n\n/**\n *\n * @param component - the component to register\n * @returns whether or not the component is registered successfully\n *\n * @internal\n */\nexport function _registerComponent<T extends Name>(\n component: Component<T>\n): boolean {\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 false;\n }\n\n _components.set(componentName, component);\n\n // add the component to existing app instances\n for (const app of _apps.values()) {\n _addComponent(app as FirebaseAppImpl, component);\n }\n\n return true;\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n *\n * @returns the provider for the service with the matching name\n *\n * @internal\n */\nexport function _getProvider<T extends Name>(\n app: FirebaseApp,\n name: T\n): Provider<T> {\n const heartbeatController = (app as FirebaseAppImpl).container\n .getProvider('heartbeat')\n .getImmediate({ optional: true });\n if (heartbeatController) {\n void heartbeatController.triggerHeartbeat();\n }\n return (app as FirebaseAppImpl).container.getProvider(name);\n}\n\n/**\n *\n * @param app - FirebaseApp instance\n * @param name - service name\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\n *\n * @internal\n */\nexport function _removeServiceInstance<T extends Name>(\n app: FirebaseApp,\n name: T,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n): void {\n _getProvider(app, name).clearInstance(instanceIdentifier);\n}\n\n/**\n * Test only\n *\n * @internal\n */\nexport function _clearComponents(): void {\n _components.clear();\n}\n\n/**\n * Exported in order to be used in app-compat package\n */\nexport { DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME };\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 NO_OPTIONS = 'no-options',\n INVALID_APP_ARGUMENT = 'invalid-app-argument',\n INVALID_LOG_ARGUMENT = 'invalid-log-argument',\n IDB_OPEN = 'idb-open',\n IDB_GET = 'idb-get',\n IDB_WRITE = 'idb-set',\n IDB_DELETE = 'idb-delete'\n}\n\nconst ERRORS: ErrorMap<AppError> = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call initializeApp() first',\n [AppError.BAD_APP_NAME]: \"Illegal App name: '{$appName}\",\n [AppError.DUPLICATE_APP]:\n \"Firebase App named '{$appName}' already exists with different options or config\",\n [AppError.APP_DELETED]: \"Firebase App named '{$appName}' already deleted\",\n [AppError.NO_OPTIONS]:\n 'Need to provide options, when not being deployed to hosting via source.',\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [AppError.INVALID_LOG_ARGUMENT]:\n 'First argument to `onLog` must be null or a function.',\n [AppError.IDB_OPEN]:\n 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_GET]:\n 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_WRITE]:\n 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\n [AppError.IDB_DELETE]:\n 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.'\n};\n\ninterface ErrorParams {\n [AppError.NO_APP]: { appName: string };\n [AppError.BAD_APP_NAME]: { appName: string };\n [AppError.DUPLICATE_APP]: { appName: string };\n [AppError.APP_DELETED]: { appName: string };\n [AppError.INVALID_APP_ARGUMENT]: { appName: string };\n [AppError.IDB_OPEN]: { originalErrorMessage?: string };\n [AppError.IDB_GET]: { originalErrorMessage?: string };\n [AppError.IDB_WRITE]: { originalErrorMessage?: string };\n [AppError.IDB_DELETE]: { originalErrorMessage?: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppError, ErrorParams>(\n 'app',\n 'Firebase',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport {\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { ERROR_FACTORY, AppError } from './errors';\n\nexport class FirebaseAppImpl implements FirebaseApp {\n private readonly _options: FirebaseOptions;\n private readonly _name: string;\n /**\n * Original config values passed in as a constructor parameter.\n * It is only used to compare with another config object to support idempotent initializeApp().\n *\n * Updating automaticDataCollectionEnabled on the App instance will not change its value in _config.\n */\n private readonly _config: Required<FirebaseAppSettings>;\n private _automaticDataCollectionEnabled: boolean;\n private _isDeleted = false;\n private readonly _container: ComponentContainer;\n\n constructor(\n options: FirebaseOptions,\n config: Required<FirebaseAppSettings>,\n container: ComponentContainer\n ) {\n this._options = { ...options };\n this._config = { ...config };\n this._name = config.name;\n this._automaticDataCollectionEnabled =\n config.automaticDataCollectionEnabled;\n this._container = container;\n this.container.addComponent(\n new Component('app', () => this, ComponentType.PUBLIC)\n );\n }\n\n get automaticDataCollectionEnabled(): boolean {\n this.checkDestroyed();\n return this._automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val: boolean) {\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 get config(): Required<FirebaseAppSettings> {\n this.checkDestroyed();\n return this._config;\n }\n\n get container(): ComponentContainer {\n return this._container;\n }\n\n get isDeleted(): boolean {\n return this._isDeleted;\n }\n\n set isDeleted(val: boolean) {\n this._isDeleted = val;\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 * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n FirebaseOptions,\n FirebaseAppSettings\n} from './public-types';\nimport { DEFAULT_ENTRY_NAME, PLATFORM_LOG_STRING } from './constants';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport {\n ComponentContainer,\n Component,\n Name,\n ComponentType\n} from '@firebase/component';\nimport { version } from '../../firebase/package.json';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { _apps, _components, _registerComponent } from './internal';\nimport { logger } from './logger';\nimport {\n LogLevelString,\n setLogLevel as setLogLevelImpl,\n LogCallback,\n LogOptions,\n setUserLogHandler\n} from '@firebase/logger';\nimport { deepEqual, getDefaultAppConfig } from '@firebase/util';\n\nexport { FirebaseError } from '@firebase/util';\n\n/**\n * The current SDK version.\n *\n * @public\n */\nexport const SDK_VERSION = version;\n\n/**\n * Creates and initializes a {@link @firebase/app#FirebaseApp} instance.\n *\n * See\n * {@link\n * https://firebase.google.com/docs/web/setup#add_firebase_to_your_app\n * | Add Firebase to your app} and\n * {@link\n * https://firebase.google.com/docs/web/setup#multiple-projects\n * | Initialize multiple projects} for detailed documentation.\n *\n * @example\n * ```javascript\n *\n * // Initialize default app\n * // Retrieve your own options values by adding a web app on\n * // https://console.firebase.google.com\n * initializeApp({\n * apiKey: \"AIza....\", // Auth / General Use\n * authDomain: \"YOUR_APP.firebaseapp.com\", // Auth with popup/redirect\n * databaseURL: \"https://YOUR_APP.firebaseio.com\", // Realtime Database\n * storageBucket: \"YOUR_APP.appspot.com\", // Storage\n * messagingSenderId: \"123456789\" // Cloud Messaging\n * });\n * ```\n *\n * @example\n * ```javascript\n *\n * // Initialize another app\n * const otherApp = initializeApp({\n * databaseURL: \"https://<OTHER_DATABASE_NAME>.firebaseio.com\",\n * storageBucket: \"<OTHER_STORAGE_BUCKET>.appspot.com\"\n * }, \"otherApp\");\n * ```\n *\n * @param options - Options to configure the app's services.\n * @param name - Optional name of the app to initialize. If no name\n * is provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The initialized app.\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n name?: string\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @param options - Options to configure the app's services.\n * @param config - FirebaseApp Configuration\n *\n * @public\n */\nexport function initializeApp(\n options: FirebaseOptions,\n config?: FirebaseAppSettings\n): FirebaseApp;\n/**\n * Creates and initializes a FirebaseApp instance.\n *\n * @public\n */\nexport function initializeApp(): FirebaseApp;\nexport function initializeApp(\n _options?: FirebaseOptions,\n rawConfig = {}\n): FirebaseApp {\n let options = _options;\n\n if (typeof rawConfig !== 'object') {\n const name = rawConfig;\n rawConfig = { name };\n }\n\n const config: Required<FirebaseAppSettings> = {\n name: DEFAULT_ENTRY_NAME,\n automaticDataCollectionEnabled: false,\n ...rawConfig\n };\n const name = config.name;\n\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(AppError.BAD_APP_NAME, {\n appName: String(name)\n });\n }\n\n options ||= getDefaultAppConfig();\n\n if (!options) {\n throw ERROR_FACTORY.create(AppError.NO_OPTIONS);\n }\n\n const existingApp = _apps.get(name) as FirebaseAppImpl;\n if (existingApp) {\n // return the existing app if options and config deep equal the ones in the existing app.\n if (\n deepEqual(options, existingApp.options) &&\n deepEqual(config, existingApp.config)\n ) {\n return existingApp;\n } else {\n throw ERROR_FACTORY.create(AppError.DUPLICATE_APP, { appName: name });\n }\n }\n\n const container = new ComponentContainer(name);\n for (const component of _components.values()) {\n container.addComponent(component);\n }\n\n const newApp = new FirebaseAppImpl(options, config, container);\n\n _apps.set(name, newApp);\n\n return newApp;\n}\n\n/**\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\n *\n * When called with no arguments, the default app is returned. When an app name\n * is provided, the app corresponding to that name is returned.\n *\n * An exception is thrown if the app being retrieved has not yet been\n * initialized.\n *\n * @example\n * ```javascript\n * // Return the default app\n * const app = getApp();\n * ```\n *\n * @example\n * ```javascript\n * // Return a named app\n * const otherApp = getApp(\"otherApp\");\n * ```\n *\n * @param name - Optional name of the app to return. If no name is\n * provided, the default is `\"[DEFAULT]\"`.\n *\n * @returns The app corresponding to the provided app name.\n * If no app name is provided, the default app is returned.\n *\n * @public\n */\nexport function getApp(name: string = DEFAULT_ENTRY_NAME): FirebaseApp {\n const app = _apps.get(name);\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\n return initializeApp();\n }\n if (!app) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n\n return app;\n}\n\n/**\n * A (read-only) array of all initialized apps.\n * @public\n */\nexport function getApps(): FirebaseApp[] {\n return Array.from(_apps.values());\n}\n\n/**\n * Renders this app unusable and frees the resources of all associated\n * services.\n *\n * @example\n * ```javascript\n * deleteApp(app)\n * .then(function() {\n * console.log(\"App deleted successfully\");\n * })\n * .catch(function(error) {\n * console.log(\"Error deleting app:\", error);\n * });\n * ```\n *\n * @public\n */\nexport async function deleteApp(app: FirebaseApp): Promise<void> {\n const name = app.name;\n if (_apps.has(name)) {\n _apps.delete(name);\n await Promise.all(\n (app as FirebaseAppImpl).container\n .getProviders()\n .map(provider => provider.delete())\n );\n (app as FirebaseAppImpl).isDeleted = true;\n }\n}\n\n/**\n * Registers a library's name and version for platform logging purposes.\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\n * @param version - Current version of that library.\n * @param variant - Bundle variant, e.g., node, rn, etc.\n *\n * @public\n */\nexport 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/**\n * Sets log handler for all Firebase SDKs.\n * @param logCallback - An optional custom log handler that executes user code whenever\n * the Firebase SDK makes a logging call.\n *\n * @public\n */\nexport function onLog(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(AppError.INVALID_LOG_ARGUMENT);\n }\n setUserLogHandler(logCallback, options);\n}\n\n/**\n * Sets log level for all Firebase SDKs.\n *\n * All of the log types above the current log level are captured (i.e. if\n * you set the log level to `info`, errors are logged, but `debug` and\n * `verbose` logs are not).\n *\n * @public\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n setLogLevelImpl(logLevel);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { DBSchema, openDB, IDBPDatabase } from 'idb';\nimport { AppError, ERROR_FACTORY } from './errors';\nimport { FirebaseApp } from './public-types';\nimport { HeartbeatsInIndexedDB } from './types';\nimport { logger } from './logger';\n\nconst DB_NAME = 'firebase-heartbeat-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-heartbeat-store';\n\ninterface AppDB extends DBSchema {\n 'firebase-heartbeat-store': {\n key: string;\n value: HeartbeatsInIndexedDB;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<AppDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<AppDB>> {\n if (!dbPromise) {\n dbPromise = openDB<AppDB>(DB_NAME, DB_VERSION, {\n upgrade: (db, oldVersion) => {\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 (oldVersion) {\n case 0:\n try {\n db.createObjectStore(STORE_NAME);\n } catch (e) {\n // Safari/iOS browsers throw occasional exceptions on\n // db.createObjectStore() that may be a bug. Avoid blocking\n // the rest of the app functionality.\n console.warn(e);\n }\n }\n }\n }).catch(e => {\n throw ERROR_FACTORY.create(AppError.IDB_OPEN, {\n originalErrorMessage: e.message\n });\n });\n }\n return dbPromise;\n}\n\nexport async function readHeartbeatsFromIndexedDB(\n app: FirebaseApp\n): Promise<HeartbeatsInIndexedDB | undefined> {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME);\n const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\n // We already have the value but tx.done can throw,\n // so we need to await it here to catch errors\n await tx.done;\n return result;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_GET, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nexport async function writeHeartbeatsToIndexedDB(\n app: FirebaseApp,\n heartbeatObject: HeartbeatsInIndexedDB\n): Promise<void> {\n try {\n const db = await getDbPromise();\n const tx = db.transaction(STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(STORE_NAME);\n await objectStore.put(heartbeatObject, computeKey(app));\n await tx.done;\n } catch (e) {\n if (e instanceof FirebaseError) {\n logger.warn(e.message);\n } else {\n const idbGetError = ERROR_FACTORY.create(AppError.IDB_WRITE, {\n originalErrorMessage: (e as Error)?.message\n });\n logger.warn(idbGetError.message);\n }\n }\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.name}!${app.options.appId}`;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ComponentContainer } from '@firebase/component';\nimport {\n base64urlEncodeWithoutPadding,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport {\n readHeartbeatsFromIndexedDB,\n writeHeartbeatsToIndexedDB\n} from './indexeddb';\nimport { FirebaseApp } from './public-types';\nimport {\n HeartbeatsByUserAgent,\n HeartbeatService,\n HeartbeatsInIndexedDB,\n HeartbeatStorage,\n SingleDateHeartbeat\n} from './types';\n\nconst MAX_HEADER_BYTES = 1024;\n// 30 days\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\n\nexport class HeartbeatServiceImpl implements HeartbeatService {\n /**\n * The persistence layer for heartbeats\n * Leave public for easier testing.\n */\n _storage: HeartbeatStorageImpl;\n\n /**\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\n * the header string.\n * Stores one record per date. This will be consolidated into the standard\n * format of one record per user agent string before being sent as a header.\n * Populated from indexedDB when the controller is instantiated and should\n * be kept in sync with indexedDB.\n * Leave public for easier testing.\n */\n _heartbeatsCache: HeartbeatsInIndexedDB | null = null;\n\n /**\n * the initialization promise for populating heartbeatCache.\n * If getHeartbeatsHeader() is called before the promise resolves\n * (hearbeatsCache == null), it should wait for this promise\n * Leave public for easier testing.\n */\n _heartbeatsCachePromise: Promise<HeartbeatsInIndexedDB>;\n constructor(private readonly container: ComponentContainer) {\n const app = this.container.getProvider('app').getImmediate();\n this._storage = new HeartbeatStorageImpl(app);\n this._heartbeatsCachePromise = this._storage.read().then(result => {\n this._heartbeatsCache = result;\n return result;\n });\n }\n\n /**\n * Called to report a heartbeat. The function will generate\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\n * to IndexedDB.\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\n * already logged, subsequent calls to this function in the same day will be ignored.\n */\n async triggerHeartbeat(): Promise<void> {\n const platformLogger = this.container\n .getProvider('platform-logger')\n .getImmediate();\n\n // This is the \"Firebase user agent\" string from the platform logger\n // service, not the browser user agent.\n const agent = platformLogger.getPlatformInfoString();\n const date = getUTCDateString();\n if (this._heartbeatsCache?.heartbeats == null) {\n this._heartbeatsCache = await this._heartbeatsCachePromise;\n // If we failed to construct a heartbeats cache, then return immediately.\n if (this._heartbeatsCache?.heartbeats == null) {\n return;\n }\n }\n // Do not store a heartbeat if one is already stored for this day\n // or if a header has already been sent today.\n if (\n this._heartbeatsCache.lastSentHeartbeatDate === date ||\n this._heartbeatsCache.heartbeats.some(\n singleDateHeartbeat => singleDateHeartbeat.date === date\n )\n ) {\n return;\n } else {\n // There is no entry for this date. Create one.\n this._heartbeatsCache.heartbeats.push({ date, agent });\n }\n // Remove entries older than 30 days.\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(\n singleDateHeartbeat => {\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\n const now = Date.now();\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\n }\n );\n return this._storage.overwrite(this._heartbeatsCache);\n }\n\n /**\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\n * It also clears all heartbeats from memory as well as in IndexedDB.\n *\n * NOTE: Consuming product SDKs should not send the header if this method\n * returns an empty string.\n */\n async getHeartbeatsHeader(): Promise<string> {\n if (this._heartbeatsCache === null) {\n await this._heartbeatsCachePromise;\n }\n // If it's still null or the array is empty, there is no data to send.\n if (\n this._heartbeatsCache?.heartbeats == null ||\n this._heartbeatsCache.heartbeats.length === 0\n ) {\n return '';\n }\n const date = getUTCDateString();\n // Extract as many heartbeats from the cache as will fit under the size limit.\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(\n this._heartbeatsCache.heartbeats\n );\n const headerString = base64urlEncodeWithoutPadding(\n JSON.stringify({ version: 2, heartbeats: heartbeatsToSend })\n );\n // Store last sent date to prevent another being logged/sent for the same day.\n this._heartbeatsCache.lastSentHeartbeatDate = date;\n if (unsentEntries.length > 0) {\n // Store any unsent entries if they exist.\n this._heartbeatsCache.heartbeats = unsentEntries;\n // This seems more likely than emptying the array (below) to lead to some odd state\n // since the cache isn't empty and this will be called again on the next request,\n // and is probably safest if we await it.\n await this._storage.overwrite(this._heartbeatsCache);\n } else {\n this._heartbeatsCache.heartbeats = [];\n // Do not wait for this, to reduce latency.\n void this._storage.overwrite(this._heartbeatsCache);\n }\n return headerString;\n }\n}\n\nfunction getUTCDateString(): string {\n const today = new Date();\n // Returns date format 'YYYY-MM-DD'\n return today.toISOString().substring(0, 10);\n}\n\nexport function extractHeartbeatsForHeader(\n heartbeatsCache: SingleDateHeartbeat[],\n maxSize = MAX_HEADER_BYTES\n): {\n heartbeatsToSend: HeartbeatsByUserAgent[];\n unsentEntries: SingleDateHeartbeat[];\n} {\n // Heartbeats grouped by user agent in the standard format to be sent in\n // the header.\n const heartbeatsToSend: HeartbeatsByUserAgent[] = [];\n // Single date format heartbeats that are not sent.\n let unsentEntries = heartbeatsCache.slice();\n for (const singleDateHeartbeat of heartbeatsCache) {\n // Look for an existing entry with the same user agent.\n const heartbeatEntry = heartbeatsToSend.find(\n hb => hb.agent === singleDateHeartbeat.agent\n );\n if (!heartbeatEntry) {\n // If no entry for this user agent exists, create one.\n heartbeatsToSend.push({\n agent: singleDateHeartbeat.agent,\n dates: [singleDateHeartbeat.date]\n });\n if (countBytes(heartbeatsToSend) > maxSize) {\n // If the header would exceed max size, remove the added heartbeat\n // entry and stop adding to the header.\n heartbeatsToSend.pop();\n break;\n }\n } else {\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\n // If the header would exceed max size, remove the added date\n // and stop adding to the header.\n if (countBytes(heartbeatsToSend) > maxSize) {\n heartbeatEntry.dates.pop();\n break;\n }\n }\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\n // quota and the loop breaks early.)\n unsentEntries = unsentEntries.slice(1);\n }\n return {\n heartbeatsToSend,\n unsentEntries\n };\n}\n\nexport class HeartbeatStorageImpl implements HeartbeatStorage {\n private _canUseIndexedDBPromise: Promise<boolean>;\n constructor(public app: FirebaseApp) {\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\n }\n async runIndexedDBEnvironmentCheck(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n return false;\n } else {\n return validateIndexedDBOpenable()\n .then(() => true)\n .catch(() => false);\n }\n }\n /**\n * Read all heartbeats.\n */\n async read(): Promise<HeartbeatsInIndexedDB> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return { heartbeats: [] };\n } else {\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\n if (idbHeartbeatObject?.heartbeats) {\n return idbHeartbeatObject;\n } else {\n return { heartbeats: [] };\n }\n }\n }\n // overwrite the storage with the provided heartbeats\n async overwrite(heartbeatsObject: HeartbeatsInIndexedDB): Promise<void> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: heartbeatsObject.heartbeats\n });\n }\n }\n // add heartbeats\n async add(heartbeatsObject: HeartbeatsInIndexedDB): Promise<void> {\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\n if (!canUseIndexedDB) {\n return;\n } else {\n const existingHeartbeatsObject = await this.read();\n return writeHeartbeatsToIndexedDB(this.app, {\n lastSentHeartbeatDate:\n heartbeatsObject.lastSentHeartbeatDate ??\n existingHeartbeatsObject.lastSentHeartbeatDate,\n heartbeats: [\n ...existingHeartbeatsObject.heartbeats,\n ...heartbeatsObject.heartbeats\n ]\n });\n }\n }\n}\n\n/**\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\n * in a platform logging header JSON object, stringified, and converted\n * to base 64.\n */\nexport function countBytes(heartbeatsCache: HeartbeatsByUserAgent[]): number {\n // base64 has a restricted set of characters, all of which should be 1 byte.\n return base64urlEncodeWithoutPadding(\n // heartbeatsCache wrapper properties\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })\n ).length;\n}\n","/**\n * Firebase App\n *\n * @remarks This package coordinates the communication between the different Firebase components\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerCoreComponents } from './registerCoreComponents';\n\nexport * from './api';\nexport * from './internal';\nexport * from './public-types';\n\nregisterCoreComponents('__RUNTIME_ENV__');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseOptions } from './public-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstantiationMode,\n Name\n} from '@firebase/component';\nimport {\n deleteApp,\n _addComponent,\n _addOrOverwriteComponent,\n _DEFAULT_ENTRY_NAME,\n _FirebaseAppInternal as _FirebaseAppExp\n} from '@firebase/app';\nimport { _FirebaseService, _FirebaseNamespace } from './types';\nimport { Compat } from '@firebase/util';\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface _FirebaseApp {\n /**\n * The (read-only) name (identifier) for this App. '[DEFAULT]' is the default\n * App.\n */\n name: string;\n\n /**\n * The (read-only) configuration options from the app initialization.\n */\n options: FirebaseOptions;\n\n /**\n * The settable config flag for GDPR opt-in/opt-out\n */\n automaticDataCollectionEnabled: boolean;\n\n /**\n * Make the given App unusable and free resources.\n */\n delete(): Promise<void>;\n}\n/**\n * Global context object for a collection of services using\n * a shared authentication state.\n *\n * marked as internal because it references internal types exported from @firebase/app\n * @internal\n */\nexport class FirebaseAppImpl implements Compat<_FirebaseAppExp>, _FirebaseApp {\n private container: ComponentContainer;\n\n constructor(\n readonly _delegate: _FirebaseAppExp,\n private readonly firebase: _FirebaseNamespace\n ) {\n // add itself to container\n _addComponent(\n _delegate,\n new Component('app-compat', () => this, ComponentType.PUBLIC)\n );\n\n this.container = _delegate.container;\n }\n\n get automaticDataCollectionEnabled(): boolean {\n return this._delegate.automaticDataCollectionEnabled;\n }\n\n set automaticDataCollectionEnabled(val) {\n this._delegate.automaticDataCollectionEnabled = val;\n }\n\n get name(): string {\n return this._delegate.name;\n }\n\n get options(): FirebaseOptions {\n return this._delegate.options;\n }\n\n delete(): Promise<void> {\n return new Promise<void>(resolve => {\n this._delegate.checkDestroyed();\n resolve();\n }).then(() => {\n this.firebase.INTERNAL.removeApp(this.name);\n return deleteApp(this._delegate);\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._delegate.checkDestroyed();\n\n // Initialize instance if InstatiationMode is `EXPLICIT`.\n const provider = this._delegate.container.getProvider(name as Name);\n if (\n !provider.isInitialized() &&\n provider.getComponent()?.instantiationMode === InstantiationMode.EXPLICIT\n ) {\n provider.initialize();\n }\n\n // getImmediate will always succeed because _getService is only called for registered components.\n return provider.getImmediate({\n identifier: instanceIdentifier\n }) as unknown as _FirebaseService;\n }\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 it again.\n *\n * NOTE: currently only firestore uses 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 this._delegate.container\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .getProvider(name as any)\n .clearInstance(instanceIdentifier);\n }\n\n /**\n * @param component the component being added to this app's container\n * @internal\n */\n _addComponent(component: Component): void {\n _addComponent(this._delegate, component);\n }\n\n _addOrOverwriteComponent(component: Component): void {\n _addOrOverwriteComponent(this._delegate, component);\n }\n\n toJSON(): object {\n return {\n name: this.name,\n automaticDataCollectionEnabled: this.automaticDataCollectionEnabled,\n options: this.options\n };\n }\n}\n\n// TODO: investigate why the following needs to be commented out\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\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.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-compat',\n 'Firebase',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, FirebaseOptions } from './public-types';\nimport {\n _FirebaseNamespace,\n _FirebaseService,\n FirebaseServiceNamespace\n} from './types';\nimport * as modularAPIs from '@firebase/app';\nimport { _FirebaseAppInternal as _FirebaseAppExp } from '@firebase/app';\nimport { Component, ComponentType, Name } from '@firebase/component';\n\nimport { deepExtend, contains } from '@firebase/util';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport { FirebaseAppLiteImpl } from './lite/firebaseAppLite';\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: initializeAppCompat,\n // @ts-ignore\n app,\n registerVersion: modularAPIs.registerVersion,\n setLogLevel: modularAPIs.setLogLevel,\n onLog: modularAPIs.onLog,\n // @ts-ignore\n apps: null,\n SDK_VERSION: modularAPIs.SDK_VERSION,\n INTERNAL: {\n registerComponent: registerComponentCompat,\n removeApp,\n useAsService,\n modularAPIs\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 || modularAPIs._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 /**\n * Create a new App instance (name must be unique).\n *\n * This function is idempotent. It can be called more than once and return the same instance using the same options and config.\n */\n function initializeAppCompat(\n options: FirebaseOptions,\n rawConfig = {}\n ): FirebaseApp {\n const app = modularAPIs.initializeApp(\n options,\n rawConfig\n ) as _FirebaseAppExp;\n\n if (contains(apps, app.name)) {\n return apps[app.name];\n }\n\n const appCompat = new firebaseAppImpl(app, namespace);\n apps[app.name] = appCompat;\n return appCompat;\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 registerComponentCompat<T extends Name>(\n component: Component<T>\n ): FirebaseServiceNamespace<_FirebaseService> | null {\n const componentName = component.name;\n const componentNameWithoutCompat = componentName.replace('-compat', '');\n if (\n modularAPIs._registerComponent(component) &&\n component.type === ComponentType.PUBLIC\n ) {\n // create service namespace for public components\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)[componentNameWithoutCompat] !== '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)[componentNameWithoutCompat]();\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)[componentNameWithoutCompat] = serviceNamespace;\n\n // Patch the FirebaseAppImpl prototype\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (firebaseAppImpl.prototype as any)[componentNameWithoutCompat] =\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 return component.type === ComponentType.PUBLIC\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (namespace as any)[componentNameWithoutCompat]\n : null;\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseNamespace } from './public-types';\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.INTERNAL = {\n ...namespace.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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app-compat');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseNamespace } from './public-types';\nimport { isBrowser } from '@firebase/util';\nimport { firebase as firebaseNamespace } from './firebaseNamespace';\nimport { logger } from './logger';\nimport { registerCoreComponents } from './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 firebase = firebaseNamespace;\n\nregisterCoreComponents();\n\n// eslint-disable-next-line import/no-default-export\nexport default firebase;\n\nexport { _FirebaseNamespace, _FirebaseService } from './types';\nexport { FirebaseApp, FirebaseNamespace } from './public-types';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerVersion } from '@firebase/app';\n\nimport { name, version } from '../package.json';\n\nexport function registerCoreComponents(variant?: string): void {\n // Register `app` package.\n registerVersion(name, version, variant);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase from '@firebase/app-compat';\nimport { name, version } from '../../package.json';\n\nfirebase.registerVersion(name, version, 'app-compat');\n\nexport default firebase;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from './constants';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n NOT_REGISTERED = 'not-registered',\n INSTALLATION_NOT_FOUND = 'installation-not-found',\n REQUEST_FAILED = 'request-failed',\n APP_OFFLINE = 'app-offline',\n DELETE_PENDING_REGISTRATION = 'delete-pending-registration'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.NOT_REGISTERED]: 'Firebase Installation is not registered.',\n [ErrorCode.INSTALLATION_NOT_FOUND]: 'Firebase Installation not found.',\n [ErrorCode.REQUEST_FAILED]:\n '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\n [ErrorCode.APP_OFFLINE]: 'Could not process request. Application offline.',\n [ErrorCode.DELETE_PENDING_REGISTRATION]:\n \"Can't delete installation while there is a pending registration request.\"\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.REQUEST_FAILED]: {\n requestName: string;\n [index: string]: string | number; // to make Typescript 3.8 happy\n } & ServerErrorData;\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n SERVICE,\n SERVICE_NAME,\n ERROR_DESCRIPTION_MAP\n);\n\nexport interface ServerErrorData {\n serverCode: number;\n serverMessage: string;\n serverStatus: string;\n}\n\nexport type ServerError = FirebaseError & { customData: 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\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';\nimport { AppConfig } from '../interfaces/installation-impl';\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Returns a 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppConfig } from '../interfaces/installation-impl';\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getKey } from '../util/get-key';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { IdChangeCallbackFn } from '../api';\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DBSchema, IDBPDatabase, openDB } from 'idb';\nimport { AppConfig } from '../interfaces/installation-impl';\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\ninterface InstallationsDB extends DBSchema {\n 'firebase-installations-store': {\n key: string;\n value: InstallationEntry | undefined;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<InstallationsDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<InstallationsDB>> {\n if (!dbPromise) {\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n upgrade: (db, oldVersion) => {\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 (oldVersion) {\n case 0:\n db.createObjectStore(OBJECT_STORE_NAME);\n }\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) as Promise<InstallationEntry>;\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)) as InstallationEntry;\n await objectStore.put(value, key);\n await tx.done;\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.done;\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(\n key\n )) as InstallationEntry;\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.done;\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.done;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createInstallationRequest } from '../functions/create-installation-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\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 installations: FirebaseInstallationsImpl\n): Promise<InstallationEntryWithRegistrationPromise> {\n let registrationPromise: Promise<RegisteredInstallationEntry> | undefined;\n\n const installationEntry = await update(installations.appConfig, oldEntry => {\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\n const entryWithPromise = triggerRegistrationIfNecessary(\n installations,\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 installations: FirebaseInstallationsImpl,\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 installations,\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(installations)\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 installations: FirebaseInstallationsImpl,\n installationEntry: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n try {\n const registeredInstallationEntry = await createInstallationRequest(\n installations,\n installationEntry\n );\n return set(installations.appConfig, registeredInstallationEntry);\n } catch (e) {\n if (isServerError(e) && e.customData.serverCode === 409) {\n // Server returned a \"FID can not be used\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n // Registration failed. Set FID as not registered.\n await set(installations.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 installations: FirebaseInstallationsImpl\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(\n installations.appConfig\n );\n while (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n // createInstallation request still in progress.\n await sleep(100);\n\n entry = await updateInstallationRequest(installations.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 { installationEntry, registrationPromise } =\n await getInstallationEntry(installations);\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CreateInstallationResponse } from '../interfaces/api-response';\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';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\n\nexport async function createInstallationRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n { fid }: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n const endpoint = getInstallationsEndpoint(appConfig);\n\n const headers = getHeaders(appConfig);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\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';\nimport {\n FirebaseInstallationsImpl,\n AppConfig\n} from '../interfaces/installation-impl';\n\nexport async function generateAuthTokenRequest(\n { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\n\n const headers = getHeadersWithAuth(appConfig, installationEntry);\n\n // If heartbeat service exists, add the heartbeat string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers.append('x-firebase-client', heartbeatsHeader);\n }\n }\n\n const body = {\n installation: {\n sdkVersion: PACKAGE_VERSION,\n appId: appConfig.appId\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 =\n extractAuthTokenInfoFromResponse(responseValue);\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { generateAuthTokenRequest } from '../functions/generate-auth-token-request';\nimport {\n AppConfig,\n FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\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 installations: FirebaseInstallationsImpl,\n forceRefresh = false\n): Promise<CompletedAuthToken> {\n let tokenPromise: Promise<CompletedAuthToken> | undefined;\n const entry = await update(installations.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(installations, 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(installations, 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 installations: FirebaseInstallationsImpl,\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(installations.appConfig);\n while (entry.authToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // generateAuthToken still in progress.\n await sleep(100);\n\n entry = await updateAuthTokenRequest(installations.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(installations, 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 installations: FirebaseInstallationsImpl,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n try {\n const authToken = await generateAuthTokenRequest(\n installations,\n installationEntry\n );\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken\n };\n await set(installations.appConfig, updatedInstallationEntry);\n return authToken;\n } catch (e) {\n if (\n isServerError(e) &&\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)\n ) {\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\n // Generate a new ID next time.\n await remove(installations.appConfig);\n } else {\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n await set(installations.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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Returns a Firebase Installations auth token, identifying the current\n * Firebase Installation.\n * @param installations - The `Installations` instance.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getToken(\n installations: Installations,\n forceRefresh = false\n): Promise<string> {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n await completeInstallationRegistration(installationsImpl);\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(installationsImpl, forceRefresh);\n return authToken.token;\n}\n\nasync function completeInstallationRegistration(\n installations: FirebaseInstallationsImpl\n): Promise<void> {\n const { registrationPromise } = await getInstallationEntry(installations);\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\nimport { FirebaseError } from '@firebase/util';\nimport { AppConfig } from '../interfaces/installation-impl';\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, _getProvider } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstanceFactory,\n ComponentContainer\n} from '@firebase/component';\nimport { getId, getToken } from '../api/index';\nimport { _FirebaseInstallationsInternal } from '../interfaces/public-types';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { extractAppConfig } from '../helpers/extract-app-config';\n\nconst INSTALLATIONS_NAME = 'installations';\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\n\nconst publicFactory: InstanceFactory<'installations'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Throws if app isn't configured properly.\n const appConfig = extractAppConfig(app);\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n\n const installationsImpl: FirebaseInstallationsImpl = {\n app,\n appConfig,\n heartbeatServiceProvider,\n _delete: () => Promise.resolve()\n };\n return installationsImpl;\n};\n\nconst internalFactory: InstanceFactory<'installations-internal'> = (\n container: ComponentContainer\n) => {\n const app = container.getProvider('app').getImmediate();\n // Internal FIS instance relies on public FIS instance.\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\n\n const installationsInternal: _FirebaseInstallationsInternal = {\n getId: () => getId(installations),\n getToken: (forceRefresh?: boolean) => getToken(installations, forceRefresh)\n };\n return installationsInternal;\n};\n\nexport function registerInstallations(): void {\n _registerComponent(\n new Component(INSTALLATIONS_NAME, publicFactory, ComponentType.PUBLIC)\n );\n _registerComponent(\n new Component(\n INSTALLATIONS_NAME_INTERNAL,\n internalFactory,\n ComponentType.PRIVATE\n )\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Creates a Firebase Installation if there isn't one for the app and\n * returns the Installation ID.\n * @param installations - The `Installations` instance.\n *\n * @public\n */\nexport async function getId(installations: Installations): Promise<string> {\n const installationsImpl = installations as FirebaseInstallationsImpl;\n const { installationEntry, registrationPromise } = await getInstallationEntry(\n installationsImpl\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(installationsImpl).catch(console.error);\n }\n\n return installationEntry.fid;\n}\n","/**\n * The Firebase Installations Web SDK.\n * This SDK does not work in a Node.js environment.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerInstallations } from './functions/config';\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nexport * from './api';\nexport * from './interfaces/public-types';\n\nregisterInstallations();\nregisterVersion(name, version);\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\nregisterVersion(name, version, '__BUILD_TARGET__');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Analytics.\n */\nexport const ANALYTICS_TYPE = 'analytics';\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 FETCH_TIMEOUT_MILLIS = 60 * 1000;\n\nexport const DYNAMIC_CONFIG_URL =\n 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';\n\nexport const GTAG_URL = 'https://www.googletagmanager.com/gtag/js';\n\nexport const enum GtagCommand {\n EVENT = 'event',\n SET = 'set',\n CONFIG = 'config',\n CONSENT = 'consent',\n GET = 'get'\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/analytics');\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AnalyticsError {\n ALREADY_EXISTS = 'already-exists',\n ALREADY_INITIALIZED = 'already-initialized',\n ALREADY_INITIALIZED_SETTINGS = 'already-initialized-settings',\n INTEROP_COMPONENT_REG_FAILED = 'interop-component-reg-failed',\n INVALID_ANALYTICS_CONTEXT = 'invalid-analytics-context',\n INDEXEDDB_UNAVAILABLE = 'indexeddb-unavailable',\n FETCH_THROTTLE = 'fetch-throttle',\n CONFIG_FETCH_FAILED = 'config-fetch-failed',\n NO_API_KEY = 'no-api-key',\n NO_APP_ID = 'no-app-id',\n NO_CLIENT_ID = 'no-client-id',\n INVALID_GTAG_RESOURCE = 'invalid-gtag-resource'\n}\n\nconst ERRORS: ErrorMap<AnalyticsError> = {\n [AnalyticsError.ALREADY_EXISTS]:\n 'A Firebase Analytics instance with the appId {$id} ' +\n ' already exists. ' +\n 'Only one Firebase Analytics instance can be created for each appId.',\n [AnalyticsError.ALREADY_INITIALIZED]:\n 'initializeAnalytics() cannot be called again with different options than those ' +\n 'it was initially called with. It can be called again with the same options to ' +\n 'return the existing instance, or getAnalytics() can be used ' +\n 'to get a reference to the already-intialized instance.',\n [AnalyticsError.ALREADY_INITIALIZED_SETTINGS]:\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: {$reason}',\n [AnalyticsError.INVALID_ANALYTICS_CONTEXT]:\n 'Firebase Analytics is not supported in this environment. ' +\n 'Wrap initialization of analytics in analytics.isSupported() ' +\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\n [AnalyticsError.INDEXEDDB_UNAVAILABLE]:\n 'IndexedDB unavailable or restricted in this environment. ' +\n 'Wrap initialization of analytics in analytics.isSupported() ' +\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\n [AnalyticsError.FETCH_THROTTLE]:\n 'The config fetch request timed out while in an exponential backoff state.' +\n ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',\n [AnalyticsError.CONFIG_FETCH_FAILED]:\n 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',\n [AnalyticsError.NO_API_KEY]:\n 'The \"apiKey\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\n 'contain a valid API key.',\n [AnalyticsError.NO_APP_ID]:\n 'The \"appId\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\n 'contain a valid app ID.',\n [AnalyticsError.NO_CLIENT_ID]: 'The \"client_id\" field is empty.',\n [AnalyticsError.INVALID_GTAG_RESOURCE]:\n 'Trusted Types detected an invalid gtag resource: {$gtagURL}.'\n};\n\ninterface ErrorParams {\n [AnalyticsError.ALREADY_EXISTS]: { id: string };\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]: { reason: Error };\n [AnalyticsError.FETCH_THROTTLE]: { throttleEndTimeMillis: number };\n [AnalyticsError.CONFIG_FETCH_FAILED]: {\n httpStatus: number;\n responseMessage: string;\n };\n [AnalyticsError.INVALID_ANALYTICS_CONTEXT]: { errorInfo: string };\n [AnalyticsError.INDEXEDDB_UNAVAILABLE]: { errorInfo: string };\n [AnalyticsError.INVALID_GTAG_RESOURCE]: { gtagURL: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AnalyticsError, ErrorParams>(\n 'analytics',\n 'Analytics',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CustomParams,\n ControlParams,\n EventParams,\n ConsentSettings\n} from './public-types';\nimport { DynamicConfig, DataLayer, Gtag, MinimalDynamicConfig } from './types';\nimport { GtagCommand, GTAG_URL } from './constants';\nimport { logger } from './logger';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\n\n// Possible parameter types for gtag 'event' and 'config' commands\ntype GtagConfigOrEventParams = ControlParams & EventParams & CustomParams;\n\n/**\n * Verifies and creates a TrustedScriptURL.\n */\nexport function createGtagTrustedTypesScriptURL(url: string): string {\n if (!url.startsWith(GTAG_URL)) {\n const err = ERROR_FACTORY.create(AnalyticsError.INVALID_GTAG_RESOURCE, {\n gtagURL: url\n });\n logger.warn(err.message);\n return '';\n }\n return url;\n}\n\n/**\n * Makeshift polyfill for Promise.allSettled(). Resolves when all promises\n * have either resolved or rejected.\n *\n * @param promises Array of promises to wait for.\n */\nexport function promiseAllSettled<T>(\n promises: Array<Promise<T>>\n): Promise<T[]> {\n return Promise.all(promises.map(promise => promise.catch(e => e)));\n}\n\n/**\n * Creates a TrustedTypePolicy object that implements the rules passed as policyOptions.\n *\n * @param policyName A string containing the name of the policy\n * @param policyOptions Object containing implementations of instance methods for TrustedTypesPolicy, see {@link https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicy#instance_methods\n * | the TrustedTypePolicy reference documentation}.\n */\nexport function createTrustedTypesPolicy(\n policyName: string,\n policyOptions: Partial<TrustedTypePolicyOptions>\n): Partial<TrustedTypePolicy> | undefined {\n // Create a TrustedTypes policy that we can use for updating src\n // properties\n let trustedTypesPolicy: Partial<TrustedTypePolicy> | undefined;\n if (window.trustedTypes) {\n trustedTypesPolicy = window.trustedTypes.createPolicy(\n policyName,\n policyOptions\n );\n }\n return trustedTypesPolicy;\n}\n\n/**\n * Inserts gtag script tag into the page to asynchronously download gtag.\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\n */\nexport function insertScriptTag(\n dataLayerName: string,\n measurementId: string\n): void {\n const trustedTypesPolicy = createTrustedTypesPolicy(\n 'firebase-js-sdk-policy',\n {\n createScriptURL: createGtagTrustedTypesScriptURL\n }\n );\n\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\n const gtagScriptURL = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;\n (script.src as string | TrustedScriptURL) = trustedTypesPolicy\n ? (trustedTypesPolicy as TrustedTypePolicy)?.createScriptURL(gtagScriptURL)\n : gtagScriptURL;\n\n script.async = true;\n document.head.appendChild(script);\n}\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/**\n * Wrapped gtag logic when gtag is called with 'config' command.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n * @param measurementId GA Measurement ID to set config for.\n * @param gtagParams Gtag config params to set.\n */\nasync function gtagOnConfig(\n gtagCore: Gtag,\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [measurementId: string]: string },\n measurementId: string,\n gtagParams?: ControlParams & EventParams & CustomParams\n): Promise<void> {\n // If config is already fetched, we know the appId and can use it to look up what FID promise we\n /// are waiting for, and wait only on that one.\n const correspondingAppId = measurementIdToAppId[measurementId as string];\n try {\n if (correspondingAppId) {\n await initializationPromisesMap[correspondingAppId];\n } else {\n // If config is not fetched yet, wait for all configs (we don't know which one we need) and\n // find the appId (if any) corresponding to this measurementId. If there is one, wait on\n // that appId's initialization promise. If there is none, promise resolves and gtag\n // call goes through.\n const dynamicConfigResults = await promiseAllSettled(\n dynamicConfigPromisesList\n );\n const foundConfig = dynamicConfigResults.find(\n config => config.measurementId === measurementId\n );\n if (foundConfig) {\n await initializationPromisesMap[foundConfig.appId];\n }\n }\n } catch (e) {\n logger.error(e);\n }\n gtagCore(GtagCommand.CONFIG, measurementId, gtagParams);\n}\n\n/**\n * Wrapped gtag logic when gtag is called with 'event' command.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer.\n * @param initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementId GA Measurement ID to log event to.\n * @param gtagParams Params to log with this event.\n */\nasync function gtagOnEvent(\n gtagCore: Gtag,\n initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementId: string,\n gtagParams?: ControlParams & EventParams & CustomParams\n): Promise<void> {\n try {\n let initializationPromisesToWaitFor: Array<Promise<string>> = [];\n\n // If there's a 'send_to' param, check if any ID specified matches\n // an initializeIds() promise we are waiting for.\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 // Checking 'send_to' fields requires having all measurement ID results back from\n // the dynamic config fetch.\n const dynamicConfigResults = await promiseAllSettled(\n dynamicConfigPromisesList\n );\n for (const sendToId of gaSendToList) {\n // Any fetched dynamic measurement ID that matches this 'send_to' ID\n const foundConfig = dynamicConfigResults.find(\n config => config.measurementId === sendToId\n );\n const initializationPromise =\n foundConfig && initializationPromisesMap[foundConfig.appId];\n if (initializationPromise) {\n initializationPromisesToWaitFor.push(initializationPromise);\n } else {\n // Found an item in 'send_to' that is not associated\n // directly with an FID, possibly a group. Empty this array,\n // exit the loop early, 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 initializationPromisesToWaitFor = Object.values(\n initializationPromisesMap\n );\n }\n\n // Run core gtag function with args after all relevant initialization\n // promises have been resolved.\n await Promise.all(initializationPromisesToWaitFor);\n // Workaround for http://b/141370449 - third argument cannot be undefined.\n gtagCore(GtagCommand.EVENT, measurementId, gtagParams || {});\n } catch (e) {\n logger.error(e);\n }\n}\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 initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\n */\nfunction wrapGtag(\n gtagCore: Gtag,\n /**\n * Allows wrapped gtag calls to wait on whichever intialization promises are required,\n * depending on the contents of the gtag params' `send_to` field, if any.\n */\n initializationPromisesMap: { [appId: string]: Promise<string> },\n /**\n * Wrapped gtag calls sometimes require all dynamic config fetches to have returned\n * before determining what initialization promises (which include FIDs) to wait for.\n */\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n /**\n * Wrapped gtag config calls can narrow down which initialization promise (with FID)\n * to wait for if the measurementId is already fetched, by getting the corresponding appId,\n * which is the key for the initialization promises map.\n */\n measurementIdToAppId: { [measurementId: string]: string }\n): Gtag {\n /**\n * Wrapper around gtag that ensures FID is sent with gtag calls.\n * @param command Gtag command type.\n * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.\n * @param gtagParams Params if event is EVENT/CONFIG.\n */\n async function gtagWrapper(\n command: 'config' | 'set' | 'event' | 'consent' | 'get' | string,\n ...args: unknown[]\n ): Promise<void> {\n try {\n // If event, check that relevant initialization promises have completed.\n if (command === GtagCommand.EVENT) {\n const [measurementId, gtagParams] = args;\n // If EVENT, second arg must be measurementId.\n await gtagOnEvent(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementId as string,\n gtagParams as GtagConfigOrEventParams\n );\n } else if (command === GtagCommand.CONFIG) {\n const [measurementId, gtagParams] = args;\n // If CONFIG, second arg must be measurementId.\n await gtagOnConfig(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n measurementId as string,\n gtagParams as GtagConfigOrEventParams\n );\n } else if (command === GtagCommand.CONSENT) {\n const [gtagParams] = args;\n gtagCore(GtagCommand.CONSENT, 'update', gtagParams as ConsentSettings);\n } else if (command === GtagCommand.GET) {\n const [measurementId, fieldName, callback] = args;\n gtagCore(\n GtagCommand.GET,\n measurementId as string,\n fieldName as string,\n callback as (...args: unknown[]) => void\n );\n } else if (command === GtagCommand.SET) {\n const [customParams] = args;\n // If SET, second arg must be params.\n gtagCore(GtagCommand.SET, customParams as CustomParams);\n } else {\n gtagCore(command, ...args);\n }\n } catch (e) {\n logger.error(e);\n }\n }\n return gtagWrapper as Gtag;\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 initializationPromisesMap Map of appIds to their initialization promises.\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\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 initializationPromisesMap: { [appId: string]: Promise<string> },\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [measurementId: string]: string },\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(\n gtagCore,\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId\n );\n\n return {\n gtagCore,\n wrappedGtag: window[gtagFunctionName] as Gtag\n };\n}\n\n/**\n * Returns the script tag in the DOM matching both the gtag url pattern\n * and the provided data layer name.\n */\nexport function findGtagScriptOnPage(\n dataLayerName: string\n): HTMLScriptElement | null {\n const scriptTags = window.document.getElementsByTagName('script');\n for (const tag of Object.values(scriptTags)) {\n if (\n tag.src &&\n tag.src.includes(GTAG_URL) &&\n tag.src.includes(dataLayerName)\n ) {\n return tag;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Most logic is copied from packages/remote-config/src/client/retrying_client.ts\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { DynamicConfig, ThrottleMetadata, MinimalDynamicConfig } from './types';\nimport { FirebaseError, calculateBackoffMillis } from '@firebase/util';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { DYNAMIC_CONFIG_URL, FETCH_TIMEOUT_MILLIS } from './constants';\nimport { logger } from './logger';\n\n// App config fields needed by analytics.\nexport interface AppFields {\n appId: string;\n apiKey: string;\n measurementId?: string;\n}\n\n/**\n * Backoff factor for 503 errors, which we want to be conservative about\n * to avoid overloading servers. Each retry interval will be\n * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one\n * will be ~30 seconds (with fuzzing).\n */\nexport const LONG_RETRY_FACTOR = 30;\n\n/**\n * Base wait interval to multiplied by backoffFactor^backoffCount.\n */\nconst BASE_INTERVAL_MILLIS = 1000;\n\n/**\n * Stubbable retry data storage class.\n */\nclass RetryData {\n constructor(\n public throttleMetadata: { [appId: string]: ThrottleMetadata } = {},\n public intervalMillis: number = BASE_INTERVAL_MILLIS\n ) {}\n\n getThrottleMetadata(appId: string): ThrottleMetadata {\n return this.throttleMetadata[appId];\n }\n\n setThrottleMetadata(appId: string, metadata: ThrottleMetadata): void {\n this.throttleMetadata[appId] = metadata;\n }\n\n deleteThrottleMetadata(appId: string): void {\n delete this.throttleMetadata[appId];\n }\n}\n\nconst defaultRetryData = new RetryData();\n\n/**\n * Set GET request headers.\n * @param apiKey App API key.\n */\nfunction getHeaders(apiKey: string): Headers {\n return new Headers({\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\n/**\n * Fetches dynamic config from backend.\n * @param app Firebase app to fetch config for.\n */\nexport async function fetchDynamicConfig(\n appFields: AppFields\n): Promise<DynamicConfig> {\n const { appId, apiKey } = appFields;\n const request: RequestInit = {\n method: 'GET',\n headers: getHeaders(apiKey)\n };\n const appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);\n const response = await fetch(appUrl, request);\n if (response.status !== 200 && response.status !== 304) {\n let errorMessage = '';\n try {\n // Try to get any error message text from server response.\n const jsonResponse = (await response.json()) as {\n error?: { message?: string };\n };\n if (jsonResponse.error?.message) {\n errorMessage = jsonResponse.error.message;\n }\n } catch (_ignored) {}\n throw ERROR_FACTORY.create(AnalyticsError.CONFIG_FETCH_FAILED, {\n httpStatus: response.status,\n responseMessage: errorMessage\n });\n }\n return response.json();\n}\n\n/**\n * Fetches dynamic config from backend, retrying if failed.\n * @param app Firebase app to fetch config for.\n */\nexport async function fetchDynamicConfigWithRetry(\n app: FirebaseApp,\n // retryData and timeoutMillis are parameterized to allow passing a different value for testing.\n retryData: RetryData = defaultRetryData,\n timeoutMillis?: number\n): Promise<DynamicConfig | MinimalDynamicConfig> {\n const { appId, apiKey, measurementId } = app.options;\n\n if (!appId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_APP_ID);\n }\n\n if (!apiKey) {\n if (measurementId) {\n return {\n measurementId,\n appId\n };\n }\n throw ERROR_FACTORY.create(AnalyticsError.NO_API_KEY);\n }\n\n const throttleMetadata: ThrottleMetadata = retryData.getThrottleMetadata(\n appId\n ) || {\n backoffCount: 0,\n throttleEndTimeMillis: Date.now()\n };\n\n const signal = new AnalyticsAbortSignal();\n\n setTimeout(\n async () => {\n // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.\n signal.abort();\n },\n timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS\n );\n\n return attemptFetchDynamicConfigWithRetry(\n { appId, apiKey, measurementId },\n throttleMetadata,\n signal,\n retryData\n );\n}\n\n/**\n * Runs one retry attempt.\n * @param appFields Necessary app config fields.\n * @param throttleMetadata Ongoing metadata to determine throttling times.\n * @param signal Abort signal.\n */\nasync function attemptFetchDynamicConfigWithRetry(\n appFields: AppFields,\n { throttleEndTimeMillis, backoffCount }: ThrottleMetadata,\n signal: AnalyticsAbortSignal,\n retryData: RetryData = defaultRetryData // for testing\n): Promise<DynamicConfig | MinimalDynamicConfig> {\n const { appId, measurementId } = appFields;\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 try {\n await setAbortableTimeout(signal, throttleEndTimeMillis);\n } catch (e) {\n if (measurementId) {\n logger.warn(\n `Timed out fetching this Firebase app's measurement ID from the server.` +\n ` Falling back to the measurement ID ${measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config. [${\n (e as Error)?.message\n }]`\n );\n return { appId, measurementId };\n }\n throw e;\n }\n\n try {\n const response = await fetchDynamicConfig(appFields);\n\n // Note the SDK only clears throttle state if response is success or non-retriable.\n retryData.deleteThrottleMetadata(appId);\n\n return response;\n } catch (e) {\n const error = e as Error;\n if (!isRetriableError(error)) {\n retryData.deleteThrottleMetadata(appId);\n if (measurementId) {\n logger.warn(\n `Failed to fetch this Firebase app's measurement ID from the server.` +\n ` Falling back to the measurement ID ${measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config. [${error?.message}]`\n );\n return { appId, measurementId };\n } else {\n throw e;\n }\n }\n\n const backoffMillis =\n Number(error?.customData?.httpStatus) === 503\n ? calculateBackoffMillis(\n backoffCount,\n retryData.intervalMillis,\n LONG_RETRY_FACTOR\n )\n : calculateBackoffMillis(backoffCount, retryData.intervalMillis);\n\n // Increments backoff state.\n const throttleMetadata = {\n throttleEndTimeMillis: Date.now() + backoffMillis,\n backoffCount: backoffCount + 1\n };\n\n // Persists state.\n retryData.setThrottleMetadata(appId, throttleMetadata);\n logger.debug(`Calling attemptFetch again in ${backoffMillis} millis`);\n\n return attemptFetchDynamicConfigWithRetry(\n appFields,\n throttleMetadata,\n signal,\n retryData\n );\n }\n}\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 */\nfunction setAbortableTimeout(\n signal: AnalyticsAbortSignal,\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 // If the request completes before this timeout, the rejection has no effect.\n reject(\n ERROR_FACTORY.create(AnalyticsError.FETCH_THROTTLE, {\n throttleEndTimeMillis\n })\n );\n });\n });\n}\n\ntype RetriableError = FirebaseError & { customData: { httpStatus: string } };\n\n/**\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\n */\nfunction isRetriableError(e: Error): e is RetriableError {\n if (!(e instanceof FirebaseError) || !e.customData) {\n return false;\n }\n\n // Uses string index defined by ErrorData, which FirebaseError implements.\n const httpStatus = Number(e.customData['httpStatus']);\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\n/**\n * Shims a minimal AbortSignal (copied from Remote Config).\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 AnalyticsAbortSignal {\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 * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicConfig, Gtag, MinimalDynamicConfig } from './types';\nimport { GtagCommand, GA_FID_KEY, ORIGIN_KEY } from './constants';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { fetchDynamicConfigWithRetry } from './get-config';\nimport { logger } from './logger';\nimport { FirebaseApp } from '@firebase/app';\nimport {\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\nimport { findGtagScriptOnPage, insertScriptTag } from './helpers';\nimport { AnalyticsSettings } from './public-types';\nimport {\n defaultConsentSettingsForInit,\n _setConsentDefaultForInit,\n defaultEventParametersForInit,\n _setDefaultEventParametersForInit\n} from './functions';\n\nasync function validateIndexedDB(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n logger.warn(\n ERROR_FACTORY.create(AnalyticsError.INDEXEDDB_UNAVAILABLE, {\n errorInfo: 'IndexedDB is not available in this environment.'\n }).message\n );\n return false;\n } else {\n try {\n await validateIndexedDBOpenable();\n } catch (e) {\n logger.warn(\n ERROR_FACTORY.create(AnalyticsError.INDEXEDDB_UNAVAILABLE, {\n errorInfo: (e as Error)?.toString()\n }).message\n );\n return false;\n }\n }\n return true;\n}\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 * @param dynamicConfigPromisesList Array of all dynamic config promises.\n * @param measurementIdToAppId Maps measurementID to appID.\n * @param installations _FirebaseInstallationsInternal instance.\n *\n * @returns Measurement ID.\n */\nexport async function _initializeAnalytics(\n app: FirebaseApp,\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >,\n measurementIdToAppId: { [key: string]: string },\n installations: _FirebaseInstallationsInternal,\n gtagCore: Gtag,\n dataLayerName: string,\n options?: AnalyticsSettings\n): Promise<string> {\n const dynamicConfigPromise = fetchDynamicConfigWithRetry(app);\n // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.\n dynamicConfigPromise\n .then(config => {\n measurementIdToAppId[config.measurementId] = config.appId;\n if (\n app.options.measurementId &&\n config.measurementId !== app.options.measurementId\n ) {\n logger.warn(\n `The measurement ID in the local Firebase config (${app.options.measurementId})` +\n ` does not match the measurement ID fetched from the server (${config.measurementId}).` +\n ` To ensure analytics events are always sent to the correct Analytics property,` +\n ` update the` +\n ` measurement ID field in the local config or remove it from the local config.`\n );\n }\n })\n .catch(e => logger.error(e));\n // Add to list to track state of all dynamic config promises.\n dynamicConfigPromisesList.push(dynamicConfigPromise);\n\n const fidPromise: Promise<string | undefined> = validateIndexedDB().then(\n envIsValid => {\n if (envIsValid) {\n return installations.getId();\n } else {\n return undefined;\n }\n }\n );\n\n const [dynamicConfig, fid] = await Promise.all([\n dynamicConfigPromise,\n fidPromise\n ]);\n\n // Detect if user has already put the gtag <script> tag on this page with the passed in\n // data layer name.\n if (!findGtagScriptOnPage(dataLayerName)) {\n insertScriptTag(dataLayerName, dynamicConfig.measurementId);\n }\n\n // Detects if there are consent settings that need to be configured.\n if (defaultConsentSettingsForInit) {\n gtagCore(GtagCommand.CONSENT, 'default', defaultConsentSettingsForInit);\n _setConsentDefaultForInit(undefined);\n }\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 as any)('js', new Date());\n // User config added first. We don't want users to accidentally overwrite\n // base Firebase config properties.\n const configProperties: Record<string, unknown> = options?.config ?? {};\n\n // guard against developers accidentally setting properties with prefix `firebase_`\n configProperties[ORIGIN_KEY] = 'firebase';\n configProperties.update = true;\n\n if (fid != null) {\n configProperties[GA_FID_KEY] = fid;\n }\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 // Note: This will trigger a page_view event unless 'send_page_view' is set to false in\n // `configProperties`.\n gtagCore(GtagCommand.CONFIG, dynamicConfig.measurementId, configProperties);\n\n // Detects if there is data that will be set on every event logged from the SDK.\n if (defaultEventParametersForInit) {\n gtagCore(GtagCommand.SET, defaultEventParametersForInit);\n _setDefaultEventParametersForInit(undefined);\n }\n\n return dynamicConfig.measurementId;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SettingsOptions, Analytics, AnalyticsSettings } from './public-types';\nimport { Gtag, DynamicConfig, MinimalDynamicConfig } from './types';\nimport { getOrCreateDataLayer, wrapOrCreateGtag } from './helpers';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { areCookiesEnabled, isBrowserExtension } from '@firebase/util';\nimport { _initializeAnalytics } from './initialize-analytics';\nimport { logger } from './logger';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\n\n/**\n * Analytics Service class.\n */\nexport class AnalyticsService implements Analytics, _FirebaseService {\n constructor(public app: FirebaseApp) {}\n _delete(): Promise<void> {\n delete initializationPromisesMap[this.app.options.appId!];\n return Promise.resolve();\n }\n}\n\n/**\n * Maps appId to full initialization promise. Wrapped gtag calls must wait on\n * all or some of these, depending on the call's `send_to` param and the status\n * of the dynamic config fetches (see below).\n */\nexport let initializationPromisesMap: {\n [appId: string]: Promise<string>; // Promise contains measurement ID string.\n} = {};\n\n/**\n * List of dynamic config fetch promises. In certain cases, wrapped gtag calls\n * wait on all these to be complete in order to determine if it can selectively\n * wait for only certain initialization (FID) promises or if it must wait for all.\n */\nlet dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n> = [];\n\n/**\n * Maps fetched measurementIds to appId. Populated when the app's dynamic config\n * fetch completes. If already populated, gtag config calls can use this to\n * selectively wait for only this app's initialization promise (FID) instead of all\n * initialization promises.\n */\nconst measurementIdToAppId: { [measurementId: string]: string } = {};\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 */\nexport let 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 * @internal\n */\nexport function resetGlobalVars(\n newGlobalInitDone = false,\n newInitializationPromisesMap = {},\n newDynamicPromises = []\n): void {\n globalInitDone = newGlobalInitDone;\n initializationPromisesMap = newInitializationPromisesMap;\n dynamicConfigPromisesList = newDynamicPromises;\n dataLayerName = 'dataLayer';\n gtagName = 'gtag';\n}\n\n/**\n * For testing\n * @internal\n */\nexport function getGlobalVars(): {\n initializationPromisesMap: { [appId: string]: Promise<string> };\n dynamicConfigPromisesList: Array<\n Promise<DynamicConfig | MinimalDynamicConfig>\n >;\n} {\n return {\n initializationPromisesMap,\n dynamicConfigPromisesList\n };\n}\n\n/**\n * Configures Firebase Analytics to use custom `gtag` or `dataLayer` names.\n * Intended to be used if `gtag.js` script has been installed on\n * this page independently of Firebase Analytics, and is using non-default\n * names for either the `gtag` function or for `dataLayer`.\n * Must be called before calling `getAnalytics()` or it won't\n * have any effect.\n *\n * @public\n *\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\n/**\n * Returns true if no environment mismatch is found.\n * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT\n * error that also lists details for each mismatch found.\n */\nfunction warnOnBrowserContextMismatch(): void {\n const mismatchedEnvMessages = [];\n if (isBrowserExtension()) {\n mismatchedEnvMessages.push('This is a browser extension environment.');\n }\n if (!areCookiesEnabled()) {\n mismatchedEnvMessages.push('Cookies are not available.');\n }\n if (mismatchedEnvMessages.length > 0) {\n const details = mismatchedEnvMessages\n .map((message, index) => `(${index + 1}) ${message}`)\n .join(' ');\n const err = ERROR_FACTORY.create(AnalyticsError.INVALID_ANALYTICS_CONTEXT, {\n errorInfo: details\n });\n logger.warn(err.message);\n }\n}\n\n/**\n * Analytics instance factory.\n * @internal\n */\nexport function factory(\n app: FirebaseApp,\n installations: _FirebaseInstallationsInternal,\n options?: AnalyticsSettings\n): AnalyticsService {\n warnOnBrowserContextMismatch();\n const appId = app.options.appId;\n if (!appId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_APP_ID);\n }\n if (!app.options.apiKey) {\n if (app.options.measurementId) {\n logger.warn(\n `The \"apiKey\" field is empty in the local Firebase config. This is needed to fetch the latest` +\n ` measurement ID for this Firebase app. Falling back to the measurement ID ${app.options.measurementId}` +\n ` provided in the \"measurementId\" field in the local Firebase config.`\n );\n } else {\n throw ERROR_FACTORY.create(AnalyticsError.NO_API_KEY);\n }\n }\n if (initializationPromisesMap[appId] != null) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_EXISTS, {\n id: appId\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 getOrCreateDataLayer(dataLayerName);\n\n const { wrappedGtag, gtagCore } = wrapOrCreateGtag(\n initializationPromisesMap,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n dataLayerName,\n gtagName\n );\n wrappedGtagFunction = wrappedGtag;\n gtagCoreFunction = gtagCore;\n\n globalInitDone = true;\n }\n // Async but non-blocking.\n // This map reflects the completion state of all promises for each appId.\n initializationPromisesMap[appId] = _initializeAnalytics(\n app,\n dynamicConfigPromisesList,\n measurementIdToAppId,\n installations,\n gtagCoreFunction,\n dataLayerName,\n options\n );\n\n const analyticsInstance: AnalyticsService = new AnalyticsService(app);\n\n return analyticsInstance;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable camelcase */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport {\n Analytics,\n AnalyticsCallOptions,\n AnalyticsSettings,\n ConsentSettings,\n CustomParams,\n EventNameString,\n EventParams\n} from './public-types';\nimport { Provider } from '@firebase/component';\nimport {\n isIndexedDBAvailable,\n validateIndexedDBOpenable,\n areCookiesEnabled,\n isBrowserExtension,\n getModularInstance,\n deepEqual\n} from '@firebase/util';\nimport { ANALYTICS_TYPE, GtagCommand } from './constants';\nimport {\n AnalyticsService,\n initializationPromisesMap,\n wrappedGtagFunction\n} from './factory';\nimport { logger } from './logger';\nimport {\n logEvent as internalLogEvent,\n setCurrentScreen as internalSetCurrentScreen,\n setUserId as internalSetUserId,\n setUserProperties as internalSetUserProperties,\n setAnalyticsCollectionEnabled as internalSetAnalyticsCollectionEnabled,\n _setConsentDefaultForInit,\n _setDefaultEventParametersForInit,\n internalGetGoogleAnalyticsClientId\n} from './functions';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\n\nexport { settings } from './factory';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n [ANALYTICS_TYPE]: AnalyticsService;\n }\n}\n\n/**\n * Returns an {@link Analytics} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function getAnalytics(app: FirebaseApp = getApp()): Analytics {\n app = getModularInstance(app);\n // Dependencies\n const analyticsProvider: Provider<'analytics'> = _getProvider(\n app,\n ANALYTICS_TYPE\n );\n\n if (analyticsProvider.isInitialized()) {\n return analyticsProvider.getImmediate();\n }\n\n return initializeAnalytics(app);\n}\n\n/**\n * Returns an {@link Analytics} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function initializeAnalytics(\n app: FirebaseApp,\n options: AnalyticsSettings = {}\n): Analytics {\n // Dependencies\n const analyticsProvider: Provider<'analytics'> = _getProvider(\n app,\n ANALYTICS_TYPE\n );\n if (analyticsProvider.isInitialized()) {\n const existingInstance = analyticsProvider.getImmediate();\n if (deepEqual(options, analyticsProvider.getOptions())) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_INITIALIZED);\n }\n }\n const analyticsInstance = analyticsProvider.initialize({ options });\n return analyticsInstance;\n}\n\n/**\n * This is a public static method provided to users that wraps four different checks:\n *\n * 1. Check if it's not a browser extension environment.\n * 2. Check if cookies are enabled in current browser.\n * 3. Check if IndexedDB is supported by the browser environment.\n * 4. Check if the current browser context is valid for using `IndexedDB.open()`.\n *\n * @public\n *\n */\nexport async function isSupported(): Promise<boolean> {\n if (isBrowserExtension()) {\n return false;\n }\n if (!areCookiesEnabled()) {\n return false;\n }\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n try {\n const isDBOpenable: boolean = await validateIndexedDBOpenable();\n return isDBOpenable;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Use gtag `config` command to set `screen_name`.\n *\n * @public\n *\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param screenName - Screen name to set.\n */\nexport function setCurrentScreen(\n analyticsInstance: Analytics,\n screenName: string,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetCurrentScreen(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n screenName,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Retrieves a unique Google Analytics identifier for the web client.\n * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport async function getGoogleAnalyticsClientId(\n analyticsInstance: Analytics\n): Promise<string> {\n analyticsInstance = getModularInstance(analyticsInstance);\n return internalGetGoogleAnalyticsClientId(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!]\n );\n}\n\n/**\n * Use gtag `config` command to set `user_id`.\n *\n * @public\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param id - User ID to set.\n */\nexport function setUserId(\n analyticsInstance: Analytics,\n id: string | null,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetUserId(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n id,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Use gtag `config` command to set all params specified.\n *\n * @public\n */\nexport function setUserProperties(\n analyticsInstance: Analytics,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetUserProperties(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n properties,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Sets whether Google Analytics collection is enabled for this app on this device.\n * Sets global `window['ga-disable-analyticsId'] = true;`\n *\n * @public\n *\n * @param analyticsInstance - The {@link Analytics} instance.\n * @param enabled - If true, enables collection, if false, disables it.\n */\nexport function setAnalyticsCollectionEnabled(\n analyticsInstance: Analytics,\n enabled: boolean\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalSetAnalyticsCollectionEnabled(\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n enabled\n ).catch(e => logger.error(e));\n}\n\n/**\n * Adds data that will be set on every event logged from the SDK, including automatic ones.\n * With gtag's \"set\" command, the values passed persist on the current page and are passed with\n * all subsequent events.\n * @public\n * @param customParams - Any custom params the user may pass to gtag.js.\n */\nexport function setDefaultEventParameters(customParams: CustomParams): void {\n // Check if reference to existing gtag function on window object exists\n if (wrappedGtagFunction) {\n wrappedGtagFunction(GtagCommand.SET, customParams);\n } else {\n _setDefaultEventParametersForInit(customParams);\n }\n}\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_payment_info',\n eventParams?: {\n coupon?: EventParams['coupon'];\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n payment_type?: EventParams['payment_type'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_shipping_info',\n eventParams?: {\n coupon?: EventParams['coupon'];\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n shipping_tier?: EventParams['shipping_tier'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'add_to_cart' | 'add_to_wishlist' | 'remove_from_cart',\n eventParams?: {\n currency?: EventParams['currency'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'begin_checkout',\n eventParams?: {\n currency?: EventParams['currency'];\n coupon?: EventParams['coupon'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'checkout_progress',\n eventParams?: {\n currency?: EventParams['currency'];\n coupon?: EventParams['coupon'];\n value?: EventParams['value'];\n items?: EventParams['items'];\n checkout_step?: EventParams['checkout_step'];\n checkout_option?: EventParams['checkout_option'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See\n * {@link https://developers.google.com/analytics/devguides/collection/ga4/exceptions\n * | Measure exceptions}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'exception',\n eventParams?: {\n description?: EventParams['description'];\n fatal?: EventParams['fatal'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'generate_lead',\n eventParams?: {\n value?: EventParams['value'];\n currency?: EventParams['currency'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'login',\n eventParams?: {\n method?: EventParams['method'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See\n * {@link https://developers.google.com/analytics/devguides/collection/ga4/views\n * | Page views}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'page_view',\n eventParams?: {\n page_title?: string;\n page_location?: string;\n page_path?: string;\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'purchase' | 'refund',\n eventParams?: {\n value?: EventParams['value'];\n currency?: EventParams['currency'];\n transaction_id: EventParams['transaction_id'];\n tax?: EventParams['tax'];\n shipping?: EventParams['shipping'];\n items?: EventParams['items'];\n coupon?: EventParams['coupon'];\n affiliation?: EventParams['affiliation'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * See {@link https://firebase.google.com/docs/analytics/screenviews\n * | Track Screenviews}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'screen_view',\n eventParams?: {\n firebase_screen: EventParams['firebase_screen'];\n firebase_screen_class: EventParams['firebase_screen_class'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'search' | 'view_search_results',\n eventParams?: {\n search_term?: EventParams['search_term'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_content',\n eventParams?: {\n content_type?: EventParams['content_type'];\n item_id?: EventParams['item_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_item',\n eventParams?: {\n items?: EventParams['items'];\n item_list_name?: EventParams['item_list_name'];\n item_list_id?: EventParams['item_list_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'select_promotion' | 'view_promotion',\n eventParams?: {\n items?: EventParams['items'];\n promotion_id?: EventParams['promotion_id'];\n promotion_name?: EventParams['promotion_name'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'set_checkout_option',\n eventParams?: {\n checkout_step?: EventParams['checkout_step'];\n checkout_option?: EventParams['checkout_option'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'share',\n eventParams?: {\n method?: EventParams['method'];\n content_type?: EventParams['content_type'];\n item_id?: EventParams['item_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'sign_up',\n eventParams?: {\n method?: EventParams['method'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'timing_complete',\n eventParams?: {\n name: string;\n value: number;\n event_category?: string;\n event_label?: string;\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'view_cart' | 'view_item',\n eventParams?: {\n currency?: EventParams['currency'];\n items?: EventParams['items'];\n value?: EventParams['value'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: 'view_item_list',\n eventParams?: {\n items?: EventParams['items'];\n item_list_name?: EventParams['item_list_name'];\n item_list_id?: EventParams['item_list_id'];\n [key: string]: any;\n },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * @public\n * List of recommended event parameters can be found in\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n */\nexport function logEvent<T extends string>(\n analyticsInstance: Analytics,\n eventName: CustomEventName<T>,\n eventParams?: { [key: string]: any },\n options?: AnalyticsCallOptions\n): void;\n\n/**\n * Sends a Google Analytics event with given `eventParams`. This method\n * automatically associates this logged event with this Firebase web\n * app instance on this device.\n * List of official event parameters can be found in the gtag.js\n * reference documentation:\n * {@link https://developers.google.com/gtagjs/reference/ga4-events\n * | the GA4 reference documentation}.\n *\n * @public\n */\nexport function logEvent(\n analyticsInstance: Analytics,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): void {\n analyticsInstance = getModularInstance(analyticsInstance);\n internalLogEvent(\n wrappedGtagFunction,\n initializationPromisesMap[analyticsInstance.app.options.appId!],\n eventName,\n eventParams,\n options\n ).catch(e => logger.error(e));\n}\n\n/**\n * Any custom event name string not in the standard list of recommended\n * event names.\n * @public\n */\nexport type CustomEventName<T> = T extends EventNameString ? never : T;\n\n/**\n * Sets the applicable end user consent state for this web app across all gtag references once\n * Firebase Analytics is initialized.\n *\n * Use the {@link ConsentSettings} to specify individual consent type values. By default consent\n * types are set to \"granted\".\n * @public\n * @param consentSettings - Maps the applicable end user consent state for gtag.js.\n */\nexport function setConsent(consentSettings: ConsentSettings): void {\n // Check if reference to existing gtag function on window object exists\n if (wrappedGtagFunction) {\n wrappedGtagFunction(GtagCommand.CONSENT, 'update', consentSettings);\n } else {\n _setConsentDefaultForInit(consentSettings);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AnalyticsCallOptions,\n CustomParams,\n ControlParams,\n EventParams,\n ConsentSettings\n} from './public-types';\nimport { Gtag } from './types';\nimport { GtagCommand } from './constants';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\n\n/**\n * Event parameters to set on 'gtag' during initialization.\n */\nexport let defaultEventParametersForInit: CustomParams | undefined;\n\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 async function logEvent(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.EVENT, eventName, eventParams);\n return;\n } else {\n const measurementId = await initializationPromise;\n const params: EventParams | ControlParams = {\n ...eventParams,\n 'send_to': measurementId\n };\n gtagFunction(GtagCommand.EVENT, eventName, params);\n }\n}\n\n/**\n * Set screen_name parameter for this Google Analytics ID.\n *\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\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 async function setCurrentScreen(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n screenName: string | null,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'screen_name': screenName });\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\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 async function setUserId(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n id: string | null,\n options?: AnalyticsCallOptions\n): Promise<void> {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'user_id': id });\n return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\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 async function setUserProperties(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): Promise<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 return Promise.resolve();\n } else {\n const measurementId = await initializationPromise;\n gtagFunction(GtagCommand.CONFIG, measurementId, {\n update: true,\n 'user_properties': properties\n });\n }\n}\n\n/**\n * Retrieves a unique Google Analytics identifier for the web client.\n * See {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/config#client_id | client_id}.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n */\nexport async function internalGetGoogleAnalyticsClientId(\n gtagFunction: Gtag,\n initializationPromise: Promise<string>\n): Promise<string> {\n const measurementId = await initializationPromise;\n return new Promise((resolve, reject) => {\n gtagFunction(\n GtagCommand.GET,\n measurementId,\n 'client_id',\n (clientId: string) => {\n if (!clientId) {\n reject(ERROR_FACTORY.create(AnalyticsError.NO_CLIENT_ID));\n }\n resolve(clientId);\n }\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 async function setAnalyticsCollectionEnabled(\n initializationPromise: Promise<string>,\n enabled: boolean\n): Promise<void> {\n const measurementId = await initializationPromise;\n window[`ga-disable-${measurementId}`] = !enabled;\n}\n\n/**\n * Consent parameters to default to during 'gtag' initialization.\n */\nexport let defaultConsentSettingsForInit: ConsentSettings | undefined;\n\n/**\n * Sets the variable {@link defaultConsentSettingsForInit} for use in the initialization of\n * analytics.\n *\n * @param consentSettings Maps the applicable end user consent state for gtag.js.\n */\nexport function _setConsentDefaultForInit(\n consentSettings?: ConsentSettings\n): void {\n defaultConsentSettingsForInit = consentSettings;\n}\n\n/**\n * Sets the variable `defaultEventParametersForInit` for use in the initialization of\n * analytics.\n *\n * @param customParams Any custom params the user may pass to gtag.js.\n */\nexport function _setDefaultEventParametersForInit(\n customParams?: CustomParams\n): void {\n defaultEventParametersForInit = customParams;\n}\n","/**\n * The Firebase Analytics Web SDK.\n * This SDK does not work in a Node.js environment.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types';\nimport { factory } from './factory';\nimport { ANALYTICS_TYPE } from './constants';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\nimport { ERROR_FACTORY, AnalyticsError } from './errors';\nimport { logEvent } from './api';\nimport { name, version } from '../package.json';\nimport { AnalyticsCallOptions } from './public-types';\nimport '@firebase/installations';\n\ndeclare global {\n interface Window {\n [key: string]: unknown;\n }\n}\n\nfunction registerAnalytics(): void {\n _registerComponent(\n new Component(\n ANALYTICS_TYPE,\n (container, { options: analyticsOptions }: InstanceFactoryOptions) => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const installations = container\n .getProvider('installations-internal')\n .getImmediate();\n\n return factory(app, installations, analyticsOptions);\n },\n ComponentType.PUBLIC\n )\n );\n\n _registerComponent(\n new Component('analytics-internal', internalFactory, ComponentType.PRIVATE)\n );\n\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n\n function internalFactory(\n container: ComponentContainer\n ): FirebaseAnalyticsInternal {\n try {\n const analytics = container.getProvider(ANALYTICS_TYPE).getImmediate();\n return {\n logEvent: (\n eventName: string,\n eventParams?: { [key: string]: unknown },\n options?: AnalyticsCallOptions\n ) => logEvent(analytics, eventName, eventParams, options)\n };\n } catch (e) {\n throw ERROR_FACTORY.create(AnalyticsError.INTEROP_COMPONENT_REG_FAILED, {\n reason: e as Error\n });\n }\n }\n}\n\nregisterAnalytics();\n\nexport * from './api';\nexport * from './public-types';\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Officially recommended event names for gtag.js\n * Any other string is also allowed.\n */\nexport enum EventName {\n ADD_SHIPPING_INFO = 'add_shipping_info',\n ADD_PAYMENT_INFO = 'add_payment_info',\n ADD_TO_CART = 'add_to_cart',\n ADD_TO_WISHLIST = 'add_to_wishlist',\n BEGIN_CHECKOUT = 'begin_checkout',\n /**\n * @deprecated\n * This event name is deprecated and is unsupported in updated\n * Enhanced Ecommerce reports.\n */\n CHECKOUT_PROGRESS = 'checkout_progress',\n EXCEPTION = 'exception',\n GENERATE_LEAD = 'generate_lead',\n LOGIN = 'login',\n PAGE_VIEW = 'page_view',\n PURCHASE = 'purchase',\n REFUND = 'refund',\n REMOVE_FROM_CART = 'remove_from_cart',\n SCREEN_VIEW = 'screen_view',\n SEARCH = 'search',\n SELECT_CONTENT = 'select_content',\n SELECT_ITEM = 'select_item',\n SELECT_PROMOTION = 'select_promotion',\n /** @deprecated */\n SET_CHECKOUT_OPTION = 'set_checkout_option',\n SHARE = 'share',\n SIGN_UP = 'sign_up',\n TIMING_COMPLETE = 'timing_complete',\n VIEW_CART = 'view_cart',\n VIEW_ITEM = 'view_item',\n VIEW_ITEM_LIST = 'view_item_list',\n VIEW_PROMOTION = 'view_promotion',\n VIEW_SEARCH_RESULTS = 'view_search_results'\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, {\n _FirebaseNamespace,\n FirebaseApp\n} from '@firebase/app-compat';\nimport { FirebaseAnalytics } from '@firebase/analytics-types';\nimport { name, version } from '../package.json';\nimport { AnalyticsService } from './service';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport {\n settings as settingsExp,\n isSupported as isSupportedExp\n} from '@firebase/analytics';\nimport { EventName } from './constants';\n\nconst factory: InstanceFactory<'analytics-compat'> = (\n container: ComponentContainer\n) => {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n const analyticsServiceExp = container.getProvider('analytics').getImmediate();\n\n return new AnalyticsService(app as FirebaseApp, analyticsServiceExp);\n};\n\nexport function registerAnalytics(): void {\n const namespaceExports = {\n Analytics: AnalyticsService,\n settings: settingsExp,\n isSupported: isSupportedExp,\n // We removed this enum in exp so need to re-create it here for compat.\n EventName\n };\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component('analytics-compat', factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n}\n\nregisterAnalytics();\nfirebase.registerVersion(name, version);\n\n/**\n * Define extension behavior of `registerAnalytics`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n analytics(app?: FirebaseApp): FirebaseAnalytics;\n }\n interface FirebaseApp {\n analytics(): FirebaseAnalytics;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AnalyticsCallOptions,\n CustomParams,\n EventParams,\n FirebaseAnalytics\n} from '@firebase/analytics-types';\nimport {\n Analytics as AnalyticsServiceExp,\n logEvent as logEventExp,\n setAnalyticsCollectionEnabled as setAnalyticsCollectionEnabledExp,\n setCurrentScreen as setCurrentScreenExp,\n setUserId as setUserIdExp,\n setUserProperties as setUserPropertiesExp\n} from '@firebase/analytics';\nimport { _FirebaseService, FirebaseApp } from '@firebase/app-compat';\n\nexport class AnalyticsService implements FirebaseAnalytics, _FirebaseService {\n constructor(\n public app: FirebaseApp,\n readonly _delegate: AnalyticsServiceExp\n ) {}\n\n logEvent(\n eventName: string,\n eventParams?: EventParams | CustomParams,\n options?: AnalyticsCallOptions\n ): void {\n logEventExp(this._delegate, eventName as '', eventParams, options);\n }\n\n /**\n * @deprecated Use {@link logEvent} with `eventName` as 'screen_view' and add relevant `eventParams`.\n * See {@link https://firebase.google.com/docs/analytics/screenviews | Track Screenviews}.\n */\n setCurrentScreen(screenName: string, options?: AnalyticsCallOptions): void {\n setCurrentScreenExp(this._delegate, screenName, options);\n }\n\n setUserId(id: string, options?: AnalyticsCallOptions): void {\n setUserIdExp(this._delegate, id, options);\n }\n\n setUserProperties(\n properties: CustomParams,\n options?: AnalyticsCallOptions\n ): void {\n setUserPropertiesExp(this._delegate, properties, options);\n }\n\n setAnalyticsCollectionEnabled(enabled: boolean): void {\n setAnalyticsCollectionEnabledExp(this._delegate, enabled);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n AppCheckProvider,\n AppCheckTokenInternal,\n AppCheckTokenObserver\n} from './types';\nimport { Refresher } from './proactive-refresh';\nimport { Deferred } from '@firebase/util';\nimport { GreCAPTCHA } from './recaptcha';\nexport interface AppCheckState {\n activated: boolean;\n tokenObservers: AppCheckTokenObserver[];\n provider?: AppCheckProvider;\n token?: AppCheckTokenInternal;\n cachedTokenPromise?: Promise<AppCheckTokenInternal | undefined>;\n exchangeTokenPromise?: Promise<AppCheckTokenInternal>;\n tokenRefresher?: Refresher;\n reCAPTCHAState?: ReCAPTCHAState;\n isTokenAutoRefreshEnabled?: boolean;\n}\n\nexport interface ReCAPTCHAState {\n initialized: Deferred<GreCAPTCHA>;\n widgetId?: string;\n // True if the most recent recaptcha check succeeded.\n succeeded?: boolean;\n}\n\nexport interface DebugState {\n initialized: boolean;\n enabled: boolean;\n token?: Deferred<string>;\n}\n\nconst APP_CHECK_STATES = new Map<FirebaseApp, AppCheckState>();\nexport const DEFAULT_STATE: AppCheckState = {\n activated: false,\n tokenObservers: []\n};\n\nconst DEBUG_STATE: DebugState = {\n initialized: false,\n enabled: false\n};\n\n/**\n * Gets a reference to the state object.\n */\nexport function getStateReference(app: FirebaseApp): AppCheckState {\n return APP_CHECK_STATES.get(app) || { ...DEFAULT_STATE };\n}\n\n/**\n * Set once on initialization. The map should hold the same reference to the\n * same object until this entry is deleted.\n */\nexport function setInitialState(\n app: FirebaseApp,\n state: AppCheckState\n): AppCheckState {\n APP_CHECK_STATES.set(app, state);\n return APP_CHECK_STATES.get(app) as AppCheckState;\n}\n\n// for testing only\nexport function clearState(): void {\n APP_CHECK_STATES.clear();\n DEBUG_STATE.enabled = false;\n DEBUG_STATE.token = undefined;\n DEBUG_STATE.initialized = false;\n}\n\nexport function getDebugState(): DebugState {\n return DEBUG_STATE;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const BASE_ENDPOINT =\n 'https://content-firebaseappcheck.googleapis.com/v1';\n\nexport const EXCHANGE_RECAPTCHA_TOKEN_METHOD = 'exchangeRecaptchaV3Token';\nexport const EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD =\n 'exchangeRecaptchaEnterpriseToken';\nexport const EXCHANGE_DEBUG_TOKEN_METHOD = 'exchangeDebugToken';\n\nexport const TOKEN_REFRESH_TIME = {\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 * One day in millis, for certain error code backoffs.\n */\nexport const ONE_DAY = 24 * 60 * 60 * 1000;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\n/**\n * Port from auth proactiverefresh.js\n *\n */\n// TODO: move it to @firebase/util?\n// TODO: allow to config whether refresh should happen in the background\nexport class Refresher {\n private pending: Deferred<unknown> | null = null;\n private nextErrorWaitInterval: number;\n constructor(\n private readonly operation: () => Promise<unknown>,\n private readonly retryPolicy: (error: unknown) => boolean,\n private readonly getWaitDuration: () => number,\n private readonly lowerBound: number,\n private readonly upperBound: number\n ) {\n this.nextErrorWaitInterval = lowerBound;\n\n if (lowerBound > upperBound) {\n throw new Error(\n 'Proactive refresh lower bound greater than upper bound!'\n );\n }\n }\n\n start(): void {\n this.nextErrorWaitInterval = this.lowerBound;\n this.process(true).catch(() => {\n /* we don't care about the result */\n });\n }\n\n stop(): void {\n if (this.pending) {\n this.pending.reject('cancelled');\n this.pending = null;\n }\n }\n\n isRunning(): boolean {\n return !!this.pending;\n }\n\n private async process(hasSucceeded: boolean): Promise<void> {\n this.stop();\n try {\n this.pending = new Deferred();\n this.pending.promise.catch(_e => {\n /* ignore */\n });\n await sleep(this.getNextRun(hasSucceeded));\n\n // Why do we resolve a promise, then immediate wait for it?\n // We do it to make the promise chain cancellable.\n // We can call stop() which rejects the promise before the following line execute, which makes\n // the code jump to the catch block.\n // TODO: unit test this\n this.pending.resolve();\n await this.pending.promise;\n this.pending = new Deferred();\n this.pending.promise.catch(_e => {\n /* ignore */\n });\n await this.operation();\n\n this.pending.resolve();\n await this.pending.promise;\n\n this.process(true).catch(() => {\n /* we don't care about the result */\n });\n } catch (error) {\n if (this.retryPolicy(error)) {\n this.process(false).catch(() => {\n /* we don't care about the result */\n });\n } else {\n this.stop();\n }\n }\n }\n\n private getNextRun(hasSucceeded: boolean): number {\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 const 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\nfunction sleep(ms: number): Promise<void> {\n return new Promise<void>(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppCheckError {\n ALREADY_INITIALIZED = 'already-initialized',\n USE_BEFORE_ACTIVATION = 'use-before-activation',\n FETCH_NETWORK_ERROR = 'fetch-network-error',\n FETCH_PARSE_ERROR = 'fetch-parse-error',\n FETCH_STATUS_ERROR = 'fetch-status-error',\n STORAGE_OPEN = 'storage-open',\n STORAGE_GET = 'storage-get',\n STORAGE_WRITE = 'storage-set',\n RECAPTCHA_ERROR = 'recaptcha-error',\n THROTTLED = 'throttled'\n}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\n [AppCheckError.ALREADY_INITIALIZED]:\n 'You have already called initializeAppCheck() for FirebaseApp {$appName} with ' +\n 'different options. To avoid this error, call initializeAppCheck() with the ' +\n 'same options as when it was originally called. This will return the ' +\n 'already initialized instance.',\n [AppCheckError.USE_BEFORE_ACTIVATION]:\n 'App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. ' +\n 'Call initializeAppCheck() before instantiating other Firebase services.',\n [AppCheckError.FETCH_NETWORK_ERROR]:\n 'Fetch failed to connect to a network. Check Internet connection. ' +\n 'Original error: {$originalErrorMessage}.',\n [AppCheckError.FETCH_PARSE_ERROR]:\n 'Fetch client could not parse response.' +\n ' Original error: {$originalErrorMessage}.',\n [AppCheckError.FETCH_STATUS_ERROR]:\n 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',\n [AppCheckError.STORAGE_OPEN]:\n 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.STORAGE_GET]:\n 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.STORAGE_WRITE]:\n 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',\n [AppCheckError.RECAPTCHA_ERROR]: 'ReCAPTCHA error.',\n [AppCheckError.THROTTLED]: `Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}`\n};\n\ninterface ErrorParams {\n [AppCheckError.ALREADY_INITIALIZED]: { appName: string };\n [AppCheckError.USE_BEFORE_ACTIVATION]: { appName: string };\n [AppCheckError.FETCH_NETWORK_ERROR]: { originalErrorMessage: string };\n [AppCheckError.FETCH_PARSE_ERROR]: { originalErrorMessage: string };\n [AppCheckError.FETCH_STATUS_ERROR]: { httpStatus: number };\n [AppCheckError.STORAGE_OPEN]: { originalErrorMessage?: string };\n [AppCheckError.STORAGE_GET]: { originalErrorMessage?: string };\n [AppCheckError.STORAGE_WRITE]: { originalErrorMessage?: string };\n [AppCheckError.THROTTLED]: { time: string; httpStatus: number };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\n 'appCheck',\n 'AppCheck',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GreCAPTCHA } from './recaptcha';\nimport { getStateReference } from './state';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { FirebaseApp } from '@firebase/app';\n\nexport function getRecaptcha(\n isEnterprise: boolean = false\n): GreCAPTCHA | undefined {\n if (isEnterprise) {\n return self.grecaptcha?.enterprise;\n }\n return self.grecaptcha;\n}\n\nexport function ensureActivated(app: FirebaseApp): void {\n if (!getStateReference(app).activated) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: app.name\n });\n }\n}\n\nexport function getDurationString(durationInMillis: number): string {\n const totalSeconds = Math.round(durationInMillis / 1000);\n const days = Math.floor(totalSeconds / (3600 * 24));\n const hours = Math.floor((totalSeconds - days * 3600 * 24) / 3600);\n const minutes = Math.floor(\n (totalSeconds - days * 3600 * 24 - hours * 3600) / 60\n );\n const seconds = totalSeconds - days * 3600 * 24 - hours * 3600 - minutes * 60;\n\n let result = '';\n if (days) {\n result += pad(days) + 'd:';\n }\n if (hours) {\n result += pad(hours) + 'h:';\n }\n result += pad(minutes) + 'm:' + pad(seconds) + 's';\n return result;\n}\n\nfunction pad(value: number): string {\n if (value === 0) {\n return '00';\n }\n return value >= 10 ? value.toString() : '0' + value;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BASE_ENDPOINT,\n EXCHANGE_DEBUG_TOKEN_METHOD,\n EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD,\n EXCHANGE_RECAPTCHA_TOKEN_METHOD\n} from './constants';\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { Provider } from '@firebase/component';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Response JSON returned from AppCheck server endpoint.\n */\ninterface AppCheckResponse {\n token: string;\n // timeToLive\n ttl: string;\n}\n\ninterface AppCheckRequest {\n url: string;\n body: { [key: string]: string };\n}\n\nexport async function exchangeToken(\n { url, body }: AppCheckRequest,\n heartbeatServiceProvider: Provider<'heartbeat'>\n): Promise<AppCheckTokenInternal> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json'\n };\n // If heartbeat service exists, add heartbeat header string to the header.\n const heartbeatService = heartbeatServiceProvider.getImmediate({\n optional: true\n });\n if (heartbeatService) {\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers['X-Firebase-Client'] = heartbeatsHeader;\n }\n }\n const options: RequestInit = {\n method: 'POST',\n body: JSON.stringify(body),\n headers\n };\n let response;\n try {\n response = await fetch(url, options);\n } catch (originalError) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_NETWORK_ERROR, {\n originalErrorMessage: (originalError as Error)?.message\n });\n }\n\n if (response.status !== 200) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_STATUS_ERROR, {\n httpStatus: response.status\n });\n }\n\n let responseBody: AppCheckResponse;\n try {\n // JSON parsing throws SyntaxError if the response body isn't a JSON string.\n responseBody = await response.json();\n } catch (originalError) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n originalErrorMessage: (originalError as Error)?.message\n });\n }\n\n // Protobuf duration format.\n // https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Duration\n const match = responseBody.ttl.match(/^([\\d.]+)(s)$/);\n if (!match || !match[2] || isNaN(Number(match[1]))) {\n throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n originalErrorMessage:\n `ttl field (timeToLive) is not in standard Protobuf Duration ` +\n `format: ${responseBody.ttl}`\n });\n }\n const timeToLiveAsNumber = Number(match[1]) * 1000;\n\n const now = Date.now();\n return {\n token: responseBody.token,\n expireTimeMillis: now + timeToLiveAsNumber,\n issuedAtTimeMillis: now\n };\n}\n\nexport function getExchangeRecaptchaV3TokenRequest(\n app: FirebaseApp,\n reCAPTCHAToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n 'recaptcha_v3_token': reCAPTCHAToken\n }\n };\n}\n\nexport function getExchangeRecaptchaEnterpriseTokenRequest(\n app: FirebaseApp,\n reCAPTCHAToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n 'recaptcha_enterprise_token': reCAPTCHAToken\n }\n };\n}\n\nexport function getExchangeDebugTokenRequest(\n app: FirebaseApp,\n debugToken: string\n): AppCheckRequest {\n const { projectId, appId, apiKey } = app.options;\n\n return {\n url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_DEBUG_TOKEN_METHOD}?key=${apiKey}`,\n body: {\n // eslint-disable-next-line\n debug_token: debugToken\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { AppCheckTokenInternal } from './types';\nconst DB_NAME = 'firebase-app-check-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-app-check-store';\nconst DEBUG_TOKEN_KEY = 'debug-token';\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\nfunction getDBPromise(): Promise<IDBDatabase> {\n if (dbPromise) {\n return dbPromise;\n }\n\n dbPromise = new Promise((resolve, reject) => {\n try {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n\n request.onsuccess = event => {\n resolve((event.target as IDBOpenDBRequest).result);\n };\n\n request.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\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(STORE_NAME, {\n keyPath: 'compositeKey'\n });\n }\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n originalErrorMessage: (e as Error)?.message\n })\n );\n }\n });\n\n return dbPromise;\n}\n\nexport function readTokenFromIndexedDB(\n app: FirebaseApp\n): Promise<AppCheckTokenInternal | undefined> {\n return read(computeKey(app)) as Promise<AppCheckTokenInternal | undefined>;\n}\n\nexport function writeTokenToIndexedDB(\n app: FirebaseApp,\n token?: AppCheckTokenInternal\n): Promise<void> {\n return write(computeKey(app), token);\n}\n\nexport function writeDebugTokenToIndexedDB(token: string): Promise<void> {\n return write(DEBUG_TOKEN_KEY, token);\n}\n\nexport function readDebugTokenFromIndexedDB(): Promise<string | undefined> {\n return read(DEBUG_TOKEN_KEY) as Promise<string | undefined>;\n}\n\nasync function write(key: string, value: unknown): Promise<void> {\n const db = await getDBPromise();\n\n const transaction = db.transaction(STORE_NAME, 'readwrite');\n const store = transaction.objectStore(STORE_NAME);\n const request = store.put({\n compositeKey: key,\n value\n });\n\n return new Promise((resolve, reject) => {\n request.onsuccess = _event => {\n resolve();\n };\n\n transaction.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_WRITE, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\n });\n}\n\nasync function read(key: string): Promise<unknown> {\n const db = await getDBPromise();\n\n const transaction = db.transaction(STORE_NAME, 'readonly');\n const store = transaction.objectStore(STORE_NAME);\n const request = store.get(key);\n\n return new Promise((resolve, reject) => {\n request.onsuccess = event => {\n const result = (event.target as IDBRequest).result;\n\n if (result) {\n resolve(result.value);\n } else {\n resolve(undefined);\n }\n };\n\n transaction.onerror = event => {\n reject(\n ERROR_FACTORY.create(AppCheckError.STORAGE_GET, {\n originalErrorMessage: (event.target as IDBRequest).error?.message\n })\n );\n };\n });\n}\n\nfunction computeKey(app: FirebaseApp): string {\n return `${app.options.appId}-${app.name}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app-check');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { isIndexedDBAvailable, uuidv4 } from '@firebase/util';\nimport {\n readDebugTokenFromIndexedDB,\n readTokenFromIndexedDB,\n writeDebugTokenToIndexedDB,\n writeTokenToIndexedDB\n} from './indexeddb';\nimport { logger } from './logger';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Always resolves. In case of an error reading from indexeddb, resolve with undefined\n */\nexport async function readTokenFromStorage(\n app: FirebaseApp\n): Promise<AppCheckTokenInternal | undefined> {\n if (isIndexedDBAvailable()) {\n let token = undefined;\n try {\n token = await readTokenFromIndexedDB(app);\n } catch (e) {\n // swallow the error and return undefined\n logger.warn(`Failed to read token from IndexedDB. Error: ${e}`);\n }\n return token;\n }\n\n return undefined;\n}\n\n/**\n * Always resolves. In case of an error writing to indexeddb, print a warning and resolve the promise\n */\nexport function writeTokenToStorage(\n app: FirebaseApp,\n token?: AppCheckTokenInternal\n): Promise<void> {\n if (isIndexedDBAvailable()) {\n return writeTokenToIndexedDB(app, token).catch(e => {\n // swallow the error and resolve the promise\n logger.warn(`Failed to write token to IndexedDB. Error: ${e}`);\n });\n }\n\n return Promise.resolve();\n}\n\nexport async function readOrCreateDebugTokenFromStorage(): Promise<string> {\n /**\n * Theoretically race condition can happen if we read, then write in 2 separate transactions.\n * But it won't happen here, because this function will be called exactly once.\n */\n let existingDebugToken: string | undefined = undefined;\n try {\n existingDebugToken = await readDebugTokenFromIndexedDB();\n } catch (_e) {\n // failed to read from indexeddb. We assume there is no existing debug token, and generate a new one.\n }\n\n if (!existingDebugToken) {\n // create a new debug token\n const newToken = uuidv4();\n // We don't need to block on writing to indexeddb\n // In case persistence failed, a new debug token will be generated everytime the page is refreshed.\n // It renders the debug token useless because you have to manually register(whitelist) the new token in the firebase console again and again.\n // If you see this error trying to use debug token, it probably means you are using a browser that doesn't support indexeddb.\n // You should switch to a different browser that supports indexeddb\n writeDebugTokenToIndexedDB(newToken).catch(e =>\n logger.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)\n );\n return newToken;\n } else {\n return existingDebugToken;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getDebugState } from './state';\nimport { readOrCreateDebugTokenFromStorage } from './storage';\nimport { Deferred, getGlobal } from '@firebase/util';\n\ndeclare global {\n // var must be used for global scopes\n // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#type-checking-for-globalthis\n // eslint-disable-next-line no-var\n var FIREBASE_APPCHECK_DEBUG_TOKEN: boolean | string | undefined;\n}\n\nexport function isDebugMode(): boolean {\n const debugState = getDebugState();\n return debugState.enabled;\n}\n\nexport async function getDebugToken(): Promise<string> {\n const state = getDebugState();\n\n if (state.enabled && state.token) {\n return state.token.promise;\n } else {\n // should not happen!\n throw Error(`\n Can't get debug token in production mode.\n `);\n }\n}\n\nexport function initializeDebugMode(): void {\n const globals = getGlobal();\n const debugState = getDebugState();\n // Set to true if this function has been called, whether or not\n // it enabled debug mode.\n debugState.initialized = true;\n\n if (\n typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&\n globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true\n ) {\n return;\n }\n\n debugState.enabled = true;\n const deferredToken = new Deferred<string>();\n debugState.token = deferredToken;\n\n if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN === 'string') {\n deferredToken.resolve(globals.FIREBASE_APPCHECK_DEBUG_TOKEN);\n } else {\n deferredToken.resolve(readOrCreateDebugTokenFromStorage());\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n AppCheckTokenResult,\n AppCheckTokenInternal,\n AppCheckTokenObserver,\n ListenerType\n} from './types';\nimport { AppCheckTokenListener } from './public-types';\nimport { getStateReference } from './state';\nimport { TOKEN_REFRESH_TIME } from './constants';\nimport { Refresher } from './proactive-refresh';\nimport { ensureActivated } from './util';\nimport { exchangeToken, getExchangeDebugTokenRequest } from './client';\nimport { writeTokenToStorage } from './storage';\nimport { getDebugToken, isDebugMode } from './debug';\nimport { base64, FirebaseError } from '@firebase/util';\nimport { logger } from './logger';\nimport { AppCheckService } from './factory';\nimport { AppCheckError } from './errors';\n\n// Initial hardcoded value agreed upon across platforms for initial launch.\n// Format left open for possible dynamic error values and other fields in the future.\nexport const defaultTokenErrorData = { error: 'UNKNOWN_ERROR' };\n\n/**\n * Stringify and base64 encode token error data.\n *\n * @param tokenError Error data, currently hardcoded.\n */\nexport function formatDummyToken(\n tokenErrorData: Record<string, string>\n): string {\n return base64.encodeString(\n JSON.stringify(tokenErrorData),\n /* webSafe= */ false\n );\n}\n\n/**\n * This function always resolves.\n * The result will contain an error field if there is any error.\n * In case there is an error, the token field in the result will be populated with a dummy value\n */\nexport async function getToken(\n appCheck: AppCheckService,\n forceRefresh = false\n): Promise<AppCheckTokenResult> {\n const app = appCheck.app;\n ensureActivated(app);\n\n const state = getStateReference(app);\n\n /**\n * First check if there is a token in memory from a previous `getToken()` call.\n */\n let token: AppCheckTokenInternal | undefined = state.token;\n let error: Error | undefined = undefined;\n\n /**\n * If an invalid token was found in memory, clear token from\n * memory and unset the local variable `token`.\n */\n if (token && !isValid(token)) {\n state.token = undefined;\n token = undefined;\n }\n\n /**\n * If there is no valid token in memory, try to load token from indexedDB.\n */\n if (!token) {\n // cachedTokenPromise contains the token found in IndexedDB or undefined if not found.\n const cachedToken = await state.cachedTokenPromise;\n if (cachedToken) {\n if (isValid(cachedToken)) {\n token = cachedToken;\n } else {\n // If there was an invalid token in the indexedDB cache, clear it.\n await writeTokenToStorage(app, undefined);\n }\n }\n }\n\n // Return the cached token (from either memory or indexedDB) if it's valid\n if (!forceRefresh && token && isValid(token)) {\n return {\n token: token.token\n };\n }\n\n // Only set to true if this `getToken()` call is making the actual\n // REST call to the exchange endpoint, versus waiting for an already\n // in-flight call (see debug and regular exchange endpoint paths below)\n let shouldCallListeners = false;\n\n /**\n * DEBUG MODE\n * If debug mode is set, and there is no cached token, fetch a new App\n * Check token using the debug token, and return it directly.\n */\n if (isDebugMode()) {\n // Avoid making another call to the exchange endpoint if one is in flight.\n if (!state.exchangeTokenPromise) {\n state.exchangeTokenPromise = exchangeToken(\n getExchangeDebugTokenRequest(app, await getDebugToken()),\n appCheck.heartbeatServiceProvider\n ).finally(() => {\n // Clear promise when settled - either resolved or rejected.\n state.exchangeTokenPromise = undefined;\n });\n shouldCallListeners = true;\n }\n const tokenFromDebugExchange: AppCheckTokenInternal =\n await state.exchangeTokenPromise;\n // Write debug token to indexedDB.\n await writeTokenToStorage(app, tokenFromDebugExchange);\n // Write debug token to state.\n state.token = tokenFromDebugExchange;\n return { token: tokenFromDebugExchange.token };\n }\n\n /**\n * There are no valid tokens in memory or indexedDB and we are not in\n * debug mode.\n * Request a new token from the exchange endpoint.\n */\n try {\n // Avoid making another call to the exchange endpoint if one is in flight.\n if (!state.exchangeTokenPromise) {\n // state.provider is populated in initializeAppCheck()\n // ensureActivated() at the top of this function checks that\n // initializeAppCheck() has been called.\n state.exchangeTokenPromise = state.provider!.getToken().finally(() => {\n // Clear promise when settled - either resolved or rejected.\n state.exchangeTokenPromise = undefined;\n });\n shouldCallListeners = true;\n }\n token = await getStateReference(app).exchangeTokenPromise;\n } catch (e) {\n if ((e as FirebaseError).code === `appCheck/${AppCheckError.THROTTLED}`) {\n // Warn if throttled, but do not treat it as an error.\n logger.warn((e as FirebaseError).message);\n } else {\n // `getToken()` should never throw, but logging error text to console will aid debugging.\n logger.error(e);\n }\n // Always save error to be added to dummy token.\n error = e as FirebaseError;\n }\n\n let interopTokenResult: AppCheckTokenResult | undefined;\n if (!token) {\n // If token is undefined, there must be an error.\n // Return a dummy token along with the error.\n interopTokenResult = makeDummyTokenResult(error!);\n } else if (error) {\n if (isValid(token)) {\n // It's also possible a valid token exists, but there's also an error.\n // (Such as if the token is almost expired, tries to refresh, and\n // the exchange request fails.)\n // We add a special error property here so that the refresher will\n // count this as a failed attempt and use the backoff instead of\n // retrying repeatedly with no delay, but any 3P listeners will not\n // be hindered in getting the still-valid token.\n interopTokenResult = {\n token: token.token,\n internalError: error\n };\n } else {\n // No invalid tokens should make it to this step. Memory and cached tokens\n // are checked. Other tokens are from fresh exchanges. But just in case.\n interopTokenResult = makeDummyTokenResult(error!);\n }\n } else {\n interopTokenResult = {\n token: token.token\n };\n // write the new token to the memory state as well as the persistent storage.\n // Only do it if we got a valid new token\n state.token = token;\n await writeTokenToStorage(app, token);\n }\n\n if (shouldCallListeners) {\n notifyTokenListeners(app, interopTokenResult);\n }\n return interopTokenResult;\n}\n\n/**\n * Internal API for limited use tokens. Skips all FAC state and simply calls\n * the underlying provider.\n */\nexport async function getLimitedUseToken(\n appCheck: AppCheckService\n): Promise<AppCheckTokenResult> {\n const app = appCheck.app;\n ensureActivated(app);\n\n const { provider } = getStateReference(app);\n\n if (isDebugMode()) {\n const debugToken = await getDebugToken();\n const { token } = await exchangeToken(\n getExchangeDebugTokenRequest(app, debugToken),\n appCheck.heartbeatServiceProvider\n );\n return { token };\n } else {\n // provider is definitely valid since we ensure AppCheck was activated\n const { token } = await provider!.getToken();\n return { token };\n }\n}\n\nexport function addTokenListener(\n appCheck: AppCheckService,\n type: ListenerType,\n listener: AppCheckTokenListener,\n onError?: (error: Error) => void\n): void {\n const { app } = appCheck;\n const state = getStateReference(app);\n const tokenObserver: AppCheckTokenObserver = {\n next: listener,\n error: onError,\n type\n };\n state.tokenObservers = [...state.tokenObservers, tokenObserver];\n\n // Invoke the listener async immediately if there is a valid token\n // in memory.\n if (state.token && isValid(state.token)) {\n const validToken = state.token;\n Promise.resolve()\n .then(() => {\n listener({ token: validToken.token });\n initTokenRefresher(appCheck);\n })\n .catch(() => {\n /* we don't care about exceptions thrown in listeners */\n });\n }\n\n /**\n * Wait for any cached token promise to resolve before starting the token\n * refresher. The refresher checks to see if there is an existing token\n * in state and calls the exchange endpoint if not. We should first let the\n * IndexedDB check have a chance to populate state if it can.\n *\n * Listener call isn't needed here because cachedTokenPromise will call any\n * listeners that exist when it resolves.\n */\n\n // state.cachedTokenPromise is always populated in `activate()`.\n void state.cachedTokenPromise!.then(() => initTokenRefresher(appCheck));\n}\n\nexport function removeTokenListener(\n app: FirebaseApp,\n listener: AppCheckTokenListener\n): void {\n const state = getStateReference(app);\n\n const newObservers = state.tokenObservers.filter(\n tokenObserver => tokenObserver.next !== listener\n );\n if (\n newObservers.length === 0 &&\n state.tokenRefresher &&\n state.tokenRefresher.isRunning()\n ) {\n state.tokenRefresher.stop();\n }\n\n state.tokenObservers = newObservers;\n}\n\n/**\n * Logic to create and start refresher as needed.\n */\nfunction initTokenRefresher(appCheck: AppCheckService): void {\n const { app } = appCheck;\n const state = getStateReference(app);\n // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`\n // is not true.\n let refresher: Refresher | undefined = state.tokenRefresher;\n if (!refresher) {\n refresher = createTokenRefresher(appCheck);\n state.tokenRefresher = refresher;\n }\n if (!refresher.isRunning() && state.isTokenAutoRefreshEnabled) {\n refresher.start();\n }\n}\n\nfunction createTokenRefresher(appCheck: AppCheckService): Refresher {\n const { app } = appCheck;\n return new Refresher(\n // Keep in mind when this fails for any reason other than the ones\n // for which we should retry, it will effectively stop the proactive refresh.\n async () => {\n const state = getStateReference(app);\n // If there is no token, we will try to load it from storage and use it\n // If there is a token, we force refresh it because we know it's going to expire soon\n let result;\n if (!state.token) {\n result = await getToken(appCheck);\n } else {\n result = await getToken(appCheck, true);\n }\n\n /**\n * getToken() always resolves. In case the result has an error field defined, it means\n * the operation failed, and we should retry.\n */\n if (result.error) {\n throw result.error;\n }\n /**\n * A special `internalError` field reflects that there was an error\n * getting a new token from the exchange endpoint, but there's still a\n * previous token that's valid for now and this should be passed to 2P/3P\n * requests for a token. But we want this callback (`this.operation` in\n * `Refresher`) to throw in order to kick off the Refresher's retry\n * backoff. (Setting `hasSucceeded` to false.)\n */\n if (result.internalError) {\n throw result.internalError;\n }\n },\n () => {\n return true;\n },\n () => {\n const state = getStateReference(app);\n\n if (state.token) {\n // issuedAtTime + (50% * total TTL) + 5 minutes\n let nextRefreshTimeMillis =\n state.token.issuedAtTimeMillis +\n (state.token.expireTimeMillis - state.token.issuedAtTimeMillis) *\n 0.5 +\n 5 * 60 * 1000;\n // Do not allow refresh time to be past (expireTime - 5 minutes)\n const latestAllowableRefresh =\n state.token.expireTimeMillis - 5 * 60 * 1000;\n nextRefreshTimeMillis = Math.min(\n nextRefreshTimeMillis,\n latestAllowableRefresh\n );\n return Math.max(0, nextRefreshTimeMillis - Date.now());\n } else {\n return 0;\n }\n },\n TOKEN_REFRESH_TIME.RETRIAL_MIN_WAIT,\n TOKEN_REFRESH_TIME.RETRIAL_MAX_WAIT\n );\n}\n\nexport function notifyTokenListeners(\n app: FirebaseApp,\n token: AppCheckTokenResult\n): void {\n const observers = getStateReference(app).tokenObservers;\n\n for (const observer of observers) {\n try {\n if (observer.type === ListenerType.EXTERNAL && token.error != null) {\n // If this listener was added by a 3P call, send any token error to\n // the supplied error handler. A 3P observer always has an error\n // handler.\n observer.error!(token.error);\n } else {\n // If the token has no error field, always return the token.\n // If this is a 2P listener, return the token, whether or not it\n // has an error field.\n observer.next(token);\n }\n } catch (e) {\n // Errors in the listener function itself are always ignored.\n }\n }\n}\n\nexport function isValid(token: AppCheckTokenInternal): boolean {\n return token.expireTimeMillis - Date.now() > 0;\n}\n\nfunction makeDummyTokenResult(error: Error): AppCheckTokenResult {\n return {\n token: formatDummyToken(defaultTokenErrorData),\n error\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppCheck } from './public-types';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { FirebaseAppCheckInternal, ListenerType } from './types';\nimport {\n getToken,\n getLimitedUseToken,\n addTokenListener,\n removeTokenListener\n} from './internal-api';\nimport { Provider } from '@firebase/component';\nimport { getStateReference } from './state';\n\n/**\n * AppCheck Service class.\n */\nexport class AppCheckService implements AppCheck, _FirebaseService {\n constructor(\n public app: FirebaseApp,\n public heartbeatServiceProvider: Provider<'heartbeat'>\n ) {}\n _delete(): Promise<void> {\n const { tokenObservers } = getStateReference(this.app);\n for (const tokenObserver of tokenObservers) {\n removeTokenListener(this.app, tokenObserver.next);\n }\n return Promise.resolve();\n }\n}\n\nexport function factory(\n app: FirebaseApp,\n heartbeatServiceProvider: Provider<'heartbeat'>\n): AppCheckService {\n return new AppCheckService(app, heartbeatServiceProvider);\n}\n\nexport function internalFactory(\n appCheck: AppCheckService\n): FirebaseAppCheckInternal {\n return {\n getToken: forceRefresh => getToken(appCheck, forceRefresh),\n getLimitedUseToken: () => getLimitedUseToken(appCheck),\n addTokenListener: listener =>\n addTokenListener(appCheck, ListenerType.INTERNAL, listener),\n removeTokenListener: listener => removeTokenListener(appCheck.app, listener)\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { getStateReference } from './state';\nimport { Deferred } from '@firebase/util';\nimport { getRecaptcha, ensureActivated } from './util';\n\nexport const RECAPTCHA_URL = 'https://www.google.com/recaptcha/api.js';\nexport const RECAPTCHA_ENTERPRISE_URL =\n 'https://www.google.com/recaptcha/enterprise.js';\n\nexport function initializeV3(\n app: FirebaseApp,\n siteKey: string\n): Promise<GreCAPTCHA> {\n const initialized = new Deferred<GreCAPTCHA>();\n\n const state = getStateReference(app);\n state.reCAPTCHAState = { initialized };\n\n const divId = makeDiv(app);\n\n const grecaptcha = getRecaptcha(false);\n if (!grecaptcha) {\n loadReCAPTCHAV3Script(() => {\n const grecaptcha = getRecaptcha(false);\n\n if (!grecaptcha) {\n // it shouldn't happen.\n throw new Error('no recaptcha');\n }\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n });\n } else {\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n }\n return initialized.promise;\n}\nexport function initializeEnterprise(\n app: FirebaseApp,\n siteKey: string\n): Promise<GreCAPTCHA> {\n const initialized = new Deferred<GreCAPTCHA>();\n\n const state = getStateReference(app);\n state.reCAPTCHAState = { initialized };\n\n const divId = makeDiv(app);\n\n const grecaptcha = getRecaptcha(true);\n if (!grecaptcha) {\n loadReCAPTCHAEnterpriseScript(() => {\n const grecaptcha = getRecaptcha(true);\n\n if (!grecaptcha) {\n // it shouldn't happen.\n throw new Error('no recaptcha');\n }\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n });\n } else {\n queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n }\n return initialized.promise;\n}\n\n/**\n * Add listener to render the widget and resolve the promise when\n * the grecaptcha.ready() event fires.\n */\nfunction queueWidgetRender(\n app: FirebaseApp,\n siteKey: string,\n grecaptcha: GreCAPTCHA,\n container: string,\n initialized: Deferred<GreCAPTCHA>\n): void {\n grecaptcha.ready(() => {\n // Invisible widgets allow us to set a different siteKey for each widget,\n // so we use them to support multiple apps\n renderInvisibleWidget(app, siteKey, grecaptcha, container);\n initialized.resolve(grecaptcha);\n });\n}\n\n/**\n * Add invisible div to page.\n */\nfunction makeDiv(app: FirebaseApp): string {\n const divId = `fire_app_check_${app.name}`;\n const invisibleDiv = document.createElement('div');\n invisibleDiv.id = divId;\n invisibleDiv.style.display = 'none';\n\n document.body.appendChild(invisibleDiv);\n return divId;\n}\n\nexport async function getToken(app: FirebaseApp): Promise<string> {\n ensureActivated(app);\n\n // ensureActivated() guarantees that reCAPTCHAState is set\n const reCAPTCHAState = getStateReference(app).reCAPTCHAState!;\n const recaptcha = await reCAPTCHAState.initialized.promise;\n\n return new Promise((resolve, _reject) => {\n // Updated after initialization is complete.\n const reCAPTCHAState = getStateReference(app).reCAPTCHAState!;\n recaptcha.ready(() => {\n resolve(\n // widgetId is guaranteed to be available if reCAPTCHAState.initialized.promise resolved.\n recaptcha.execute(reCAPTCHAState.widgetId!, {\n action: 'fire_app_check'\n })\n );\n });\n });\n}\n\n/**\n *\n * @param app\n * @param container - Id of a HTML element.\n */\nfunction renderInvisibleWidget(\n app: FirebaseApp,\n siteKey: string,\n grecaptcha: GreCAPTCHA,\n container: string\n): void {\n const widgetId = grecaptcha.render(container, {\n sitekey: siteKey,\n size: 'invisible',\n // Success callback - set state\n callback: () => {\n getStateReference(app).reCAPTCHAState!.succeeded = true;\n },\n // Failure callback - set state\n 'error-callback': () => {\n getStateReference(app).reCAPTCHAState!.succeeded = false;\n }\n });\n\n const state = getStateReference(app);\n\n state.reCAPTCHAState = {\n ...state.reCAPTCHAState!, // state.reCAPTCHAState is set in the initialize()\n widgetId\n };\n}\n\nfunction loadReCAPTCHAV3Script(onload: () => void): void {\n const script = document.createElement('script');\n script.src = RECAPTCHA_URL;\n script.onload = onload;\n document.head.appendChild(script);\n}\n\nfunction loadReCAPTCHAEnterpriseScript(onload: () => void): void {\n const script = document.createElement('script');\n script.src = RECAPTCHA_ENTERPRISE_URL;\n script.onload = onload;\n document.head.appendChild(script);\n}\n\ndeclare global {\n interface Window {\n grecaptcha: GreCAPTCHATopLevel | undefined;\n }\n}\n\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise<string>;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n callback: () => void;\n 'error-callback': () => void;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _getProvider } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport {\n FirebaseError,\n issuedAtTime,\n calculateBackoffMillis\n} from '@firebase/util';\nimport {\n exchangeToken,\n getExchangeRecaptchaEnterpriseTokenRequest,\n getExchangeRecaptchaV3TokenRequest\n} from './client';\nimport { ONE_DAY } from './constants';\nimport { AppCheckError, ERROR_FACTORY } from './errors';\nimport { CustomProviderOptions } from './public-types';\nimport {\n getToken as getReCAPTCHAToken,\n initializeV3 as initializeRecaptchaV3,\n initializeEnterprise as initializeRecaptchaEnterprise\n} from './recaptcha';\nimport { getStateReference } from './state';\nimport { AppCheckProvider, AppCheckTokenInternal, ThrottleData } from './types';\nimport { getDurationString } from './util';\n\n/**\n * App Check provider that can obtain a reCAPTCHA V3 token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaV3Provider implements AppCheckProvider {\n private _app?: FirebaseApp;\n private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n /**\n * Throttle requests on certain error codes to prevent too many retries\n * in a short time.\n */\n private _throttleData: ThrottleData | null = null;\n /**\n * Create a ReCaptchaV3Provider instance.\n * @param siteKey - ReCAPTCHA V3 siteKey.\n */\n constructor(private _siteKey: string) {}\n\n /**\n * Returns an App Check token.\n * @internal\n */\n async getToken(): Promise<AppCheckTokenInternal> {\n throwIfThrottled(this._throttleData);\n\n // Top-level `getToken()` has already checked that App Check is initialized\n // and therefore this._app and this._heartbeatServiceProvider are available.\n const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n _e => {\n // reCaptcha.execute() throws null which is not very descriptive.\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n }\n );\n // Check if a failure state was set by the recaptcha \"error-callback\".\n if (!getStateReference(this._app!).reCAPTCHAState?.succeeded) {\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n }\n let result;\n try {\n result = await exchangeToken(\n getExchangeRecaptchaV3TokenRequest(this._app!, attestedClaimsToken),\n this._heartbeatServiceProvider!\n );\n } catch (e) {\n if (\n (e as FirebaseError).code?.includes(AppCheckError.FETCH_STATUS_ERROR)\n ) {\n this._throttleData = setBackoff(\n Number((e as FirebaseError).customData?.httpStatus),\n this._throttleData\n );\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(\n this._throttleData.allowRequestsAfter - Date.now()\n ),\n httpStatus: this._throttleData.httpStatus\n });\n } else {\n throw e;\n }\n }\n // If successful, clear throttle data.\n this._throttleData = null;\n return result;\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n initializeRecaptchaV3(app, this._siteKey).catch(() => {\n /* we don't care about the initialization result */\n });\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof ReCaptchaV3Provider) {\n return this._siteKey === otherProvider._siteKey;\n } else {\n return false;\n }\n }\n}\n\n/**\n * App Check provider that can obtain a reCAPTCHA Enterprise token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaEnterpriseProvider implements AppCheckProvider {\n private _app?: FirebaseApp;\n private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n /**\n * Throttle requests on certain error codes to prevent too many retries\n * in a short time.\n */\n private _throttleData: ThrottleData | null = null;\n /**\n * Create a ReCaptchaEnterpriseProvider instance.\n * @param siteKey - reCAPTCHA Enterprise score-based site key.\n */\n constructor(private _siteKey: string) {}\n\n /**\n * Returns an App Check token.\n * @internal\n */\n async getToken(): Promise<AppCheckTokenInternal> {\n throwIfThrottled(this._throttleData);\n // Top-level `getToken()` has already checked that App Check is initialized\n // and therefore this._app and this._heartbeatServiceProvider are available.\n const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n _e => {\n // reCaptcha.execute() throws null which is not very descriptive.\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n }\n );\n // Check if a failure state was set by the recaptcha \"error-callback\".\n if (!getStateReference(this._app!).reCAPTCHAState?.succeeded) {\n throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n }\n let result;\n try {\n result = await exchangeToken(\n getExchangeRecaptchaEnterpriseTokenRequest(\n this._app!,\n attestedClaimsToken\n ),\n this._heartbeatServiceProvider!\n );\n } catch (e) {\n if (\n (e as FirebaseError).code?.includes(AppCheckError.FETCH_STATUS_ERROR)\n ) {\n this._throttleData = setBackoff(\n Number((e as FirebaseError).customData?.httpStatus),\n this._throttleData\n );\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(\n this._throttleData.allowRequestsAfter - Date.now()\n ),\n httpStatus: this._throttleData.httpStatus\n });\n } else {\n throw e;\n }\n }\n // If successful, clear throttle data.\n this._throttleData = null;\n return result;\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n initializeRecaptchaEnterprise(app, this._siteKey).catch(() => {\n /* we don't care about the initialization result */\n });\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof ReCaptchaEnterpriseProvider) {\n return this._siteKey === otherProvider._siteKey;\n } else {\n return false;\n }\n }\n}\n\n/**\n * Custom provider class.\n * @public\n */\nexport class CustomProvider implements AppCheckProvider {\n private _app?: FirebaseApp;\n\n constructor(private _customProviderOptions: CustomProviderOptions) {}\n\n /**\n * @internal\n */\n async getToken(): Promise<AppCheckTokenInternal> {\n // custom provider\n const customToken = await this._customProviderOptions.getToken();\n // Try to extract IAT from custom token, in case this token is not\n // being newly issued. JWT timestamps are in seconds since epoch.\n const issuedAtTimeSeconds = issuedAtTime(customToken.token);\n // Very basic validation, use current timestamp as IAT if JWT\n // has no `iat` field or value is out of bounds.\n const issuedAtTimeMillis =\n issuedAtTimeSeconds !== null &&\n issuedAtTimeSeconds < Date.now() &&\n issuedAtTimeSeconds > 0\n ? issuedAtTimeSeconds * 1000\n : Date.now();\n\n return { ...customToken, issuedAtTimeMillis };\n }\n\n /**\n * @internal\n */\n initialize(app: FirebaseApp): void {\n this._app = app;\n }\n\n /**\n * @internal\n */\n isEqual(otherProvider: unknown): boolean {\n if (otherProvider instanceof CustomProvider) {\n return (\n this._customProviderOptions.getToken.toString() ===\n otherProvider._customProviderOptions.getToken.toString()\n );\n } else {\n return false;\n }\n }\n}\n\n/**\n * Set throttle data to block requests until after a certain time\n * depending on the failed request's status code.\n * @param httpStatus - Status code of failed request.\n * @param throttleData - `ThrottleData` object containing previous throttle\n * data state.\n * @returns Data about current throttle state and expiration time.\n */\nfunction setBackoff(\n httpStatus: number,\n throttleData: ThrottleData | null\n): ThrottleData {\n /**\n * Block retries for 1 day for the following error codes:\n *\n * 404: Likely malformed URL.\n *\n * 403:\n * - Attestation failed\n * - Wrong API key\n * - Project deleted\n */\n if (httpStatus === 404 || httpStatus === 403) {\n return {\n backoffCount: 1,\n allowRequestsAfter: Date.now() + ONE_DAY,\n httpStatus\n };\n } else {\n /**\n * For all other error codes, the time when it is ok to retry again\n * is based on exponential backoff.\n */\n const backoffCount = throttleData ? throttleData.backoffCount : 0;\n const backoffMillis = calculateBackoffMillis(backoffCount, 1000, 2);\n return {\n backoffCount: backoffCount + 1,\n allowRequestsAfter: Date.now() + backoffMillis,\n httpStatus\n };\n }\n}\n\nfunction throwIfThrottled(throttleData: ThrottleData | null): void {\n if (throttleData) {\n if (Date.now() - throttleData.allowRequestsAfter <= 0) {\n // If before, throw.\n throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n time: getDurationString(throttleData.allowRequestsAfter - Date.now()),\n httpStatus: throttleData.httpStatus\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheck,\n AppCheckOptions,\n AppCheckTokenResult,\n Unsubscribe,\n PartialObserver\n} from './public-types';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport {\n getStateReference,\n getDebugState,\n DEFAULT_STATE,\n setInitialState\n} from './state';\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\nimport { getModularInstance, ErrorFn, NextFn } from '@firebase/util';\nimport { AppCheckService } from './factory';\nimport { AppCheckProvider, ListenerType } from './types';\nimport {\n getToken as getTokenInternal,\n getLimitedUseToken as getLimitedUseTokenInternal,\n addTokenListener,\n removeTokenListener,\n isValid,\n notifyTokenListeners\n} from './internal-api';\nimport { readTokenFromStorage } from './storage';\nimport { getDebugToken, initializeDebugMode, isDebugMode } from './debug';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'app-check': AppCheckService;\n }\n}\n\nexport {\n ReCaptchaV3Provider,\n CustomProvider,\n ReCaptchaEnterpriseProvider\n} from './providers';\n\n/**\n * Activate App Check for the given app. Can be called only once per app.\n * @param app - the {@link @firebase/app#FirebaseApp} to activate App Check for\n * @param options - App Check initialization options\n * @public\n */\nexport function initializeAppCheck(\n app: FirebaseApp = getApp(),\n options: AppCheckOptions\n): AppCheck {\n app = getModularInstance(app);\n const provider = _getProvider(app, 'app-check');\n\n // Ensure initializeDebugMode() is only called once.\n if (!getDebugState().initialized) {\n initializeDebugMode();\n }\n\n // Log a message containing the debug token when `initializeAppCheck()`\n // is called in debug mode.\n if (isDebugMode()) {\n // Do not block initialization to get the token for the message.\n void getDebugToken().then(token =>\n // Not using logger because I don't think we ever want this accidentally hidden.\n console.log(\n `App Check debug token: ${token}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`\n )\n );\n }\n\n if (provider.isInitialized()) {\n const existingInstance = provider.getImmediate();\n const initialOptions = provider.getOptions() as unknown as AppCheckOptions;\n if (\n initialOptions.isTokenAutoRefreshEnabled ===\n options.isTokenAutoRefreshEnabled &&\n initialOptions.provider.isEqual(options.provider)\n ) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(AppCheckError.ALREADY_INITIALIZED, {\n appName: app.name\n });\n }\n }\n\n const appCheck = provider.initialize({ options });\n _activate(app, options.provider, options.isTokenAutoRefreshEnabled);\n // If isTokenAutoRefreshEnabled is false, do not send any requests to the\n // exchange endpoint without an explicit call from the user either directly\n // or through another Firebase library (storage, functions, etc.)\n if (getStateReference(app).isTokenAutoRefreshEnabled) {\n // Adding a listener will start the refresher and fetch a token if needed.\n // This gets a token ready and prevents a delay when an internal library\n // requests the token.\n // Listener function does not need to do anything, its base functionality\n // of calling getToken() already fetches token and writes it to memory/storage.\n addTokenListener(appCheck, ListenerType.INTERNAL, () => {});\n }\n\n return appCheck;\n}\n\n/**\n * Activate App Check\n * @param app - Firebase app to activate App Check for.\n * @param provider - reCAPTCHA v3 provider or\n * custom token provider.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. If undefined, defaults to the\n * value of `app.automaticDataCollectionEnabled`, which defaults to\n * false and can be set in the app config.\n */\nfunction _activate(\n app: FirebaseApp,\n provider: AppCheckProvider,\n isTokenAutoRefreshEnabled?: boolean\n): void {\n // Create an entry in the APP_CHECK_STATES map. Further changes should\n // directly mutate this object.\n const state = setInitialState(app, { ...DEFAULT_STATE });\n\n state.activated = true;\n state.provider = provider; // Read cached token from storage if it exists and store it in memory.\n state.cachedTokenPromise = readTokenFromStorage(app).then(cachedToken => {\n if (cachedToken && isValid(cachedToken)) {\n state.token = cachedToken;\n // notify all listeners with the cached token\n notifyTokenListeners(app, { token: cachedToken.token });\n }\n return cachedToken;\n });\n\n // Use value of global `automaticDataCollectionEnabled` (which\n // itself defaults to false if not specified in config) if\n // `isTokenAutoRefreshEnabled` param was not provided by user.\n state.isTokenAutoRefreshEnabled =\n isTokenAutoRefreshEnabled === undefined\n ? app.automaticDataCollectionEnabled\n : isTokenAutoRefreshEnabled;\n\n state.provider.initialize(app);\n}\n\n/**\n * Set whether App Check will automatically refresh tokens as needed.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. This overrides any value set\n * during `initializeAppCheck()`.\n * @public\n */\nexport function setTokenAutoRefreshEnabled(\n appCheckInstance: AppCheck,\n isTokenAutoRefreshEnabled: boolean\n): void {\n const app = appCheckInstance.app;\n const state = getStateReference(app);\n // This will exist if any product libraries have called\n // `addTokenListener()`\n if (state.tokenRefresher) {\n if (isTokenAutoRefreshEnabled === true) {\n state.tokenRefresher.start();\n } else {\n state.tokenRefresher.stop();\n }\n }\n state.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;\n}\n/**\n * Get the current App Check token. Attaches to the most recent\n * in-flight request if one is present. Returns null if no token\n * is present and no token requests are in-flight.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param forceRefresh - If true, will always try to fetch a fresh token.\n * If false, will use a cached token if found in storage.\n * @public\n */\nexport async function getToken(\n appCheckInstance: AppCheck,\n forceRefresh?: boolean\n): Promise<AppCheckTokenResult> {\n const result = await getTokenInternal(\n appCheckInstance as AppCheckService,\n forceRefresh\n );\n if (result.error) {\n throw result.error;\n }\n return { token: result.token };\n}\n\n/**\n * Requests a Firebase App Check token. This method should be used\n * only if you need to authorize requests to a non-Firebase backend.\n *\n * Returns limited-use tokens that are intended for use with your\n * non-Firebase backend endpoints that are protected with\n * <a href=\"https://firebase.google.com/docs/app-check/custom-resource-backend#replay-protection\">\n * Replay Protection</a>. This method\n * does not affect the token generation behavior of the\n * #getAppCheckToken() method.\n *\n * @param appCheckInstance - The App Check service instance.\n * @returns The limited use token.\n * @public\n */\nexport function getLimitedUseToken(\n appCheckInstance: AppCheck\n): Promise<AppCheckTokenResult> {\n return getLimitedUseTokenInternal(appCheckInstance as AppCheckService);\n}\n\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param observer - An object with `next`, `error`, and `complete`\n * properties. `next` is called with an\n * {@link AppCheckTokenResult}\n * whenever the token changes. `error` is optional and is called if an\n * error is thrown by the listener (the `next` function). `complete`\n * is unused, as the token stream is unending.\n *\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n observer: PartialObserver<AppCheckTokenResult>\n): Unsubscribe;\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param onNext - When the token changes, this function is called with an\n * {@link AppCheckTokenResult}.\n * @param onError - Optional. Called if there is an error thrown by the\n * listener (the `onNext` function).\n * @param onCompletion - Currently unused, as the token stream is unending.\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n onNext: (tokenResult: AppCheckTokenResult) => void,\n onError?: (error: Error) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Wraps `addTokenListener`/`removeTokenListener` methods in an `Observer`\n * pattern for public use.\n */\nexport function onTokenChanged(\n appCheckInstance: AppCheck,\n onNextOrObserver:\n | ((tokenResult: AppCheckTokenResult) => void)\n | PartialObserver<AppCheckTokenResult>,\n onError?: (error: Error) => void,\n /**\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the token stream is never-ending.\n * It is added only for API consistency with the observer pattern, which\n * we follow in JS APIs.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onCompletion?: () => void\n): Unsubscribe {\n let nextFn: NextFn<AppCheckTokenResult> = () => {};\n let errorFn: ErrorFn = () => {};\n if ((onNextOrObserver as PartialObserver<AppCheckTokenResult>).next != null) {\n nextFn = (\n onNextOrObserver as PartialObserver<AppCheckTokenResult>\n ).next!.bind(onNextOrObserver);\n } else {\n nextFn = onNextOrObserver as NextFn<AppCheckTokenResult>;\n }\n if (\n (onNextOrObserver as PartialObserver<AppCheckTokenResult>).error != null\n ) {\n errorFn = (\n onNextOrObserver as PartialObserver<AppCheckTokenResult>\n ).error!.bind(onNextOrObserver);\n } else if (onError) {\n errorFn = onError;\n }\n addTokenListener(\n appCheckInstance as AppCheckService,\n ListenerType.EXTERNAL,\n nextFn,\n errorFn\n );\n return () => removeTokenListener(appCheckInstance.app, nextFn);\n}\n","/**\n * The Firebase App Check Web SDK.\n *\n * @remarks\n * Firebase App Check does not work in a Node.js environment using `ReCaptchaV3Provider` or\n * `ReCaptchaEnterpriseProvider`, but can be used in Node.js if you use\n * `CustomProvider` and write your own attestation method.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\nimport { _AppCheckComponentName } from './public-types';\nimport { factory, internalFactory } from './factory';\nimport { _AppCheckInternalComponentName } from './types';\nimport { name, version } from '../package.json';\n\n// Used by other Firebase packages.\nexport { _AppCheckInternalComponentName };\n\nexport * from './api';\nexport * from './public-types';\n\nconst APP_CHECK_NAME: _AppCheckComponentName = 'app-check';\nconst APP_CHECK_NAME_INTERNAL: _AppCheckInternalComponentName =\n 'app-check-internal';\nfunction registerAppCheck(): void {\n // The public interface\n _registerComponent(\n new Component(\n APP_CHECK_NAME,\n container => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const heartbeatServiceProvider = container.getProvider('heartbeat');\n return factory(app, heartbeatServiceProvider);\n },\n ComponentType.PUBLIC\n )\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Initialize app-check-internal after app-check is initialized to make AppCheck available to\n * other Firebase SDKs\n */\n .setInstanceCreatedCallback(\n (container, _identifier, _appcheckService) => {\n container.getProvider(APP_CHECK_NAME_INTERNAL).initialize();\n }\n )\n );\n\n // The internal interface used by other Firebase products\n _registerComponent(\n new Component(\n APP_CHECK_NAME_INTERNAL,\n container => {\n const appCheck = container.getProvider('app-check').getImmediate();\n return internalFactory(appCheck);\n },\n ComponentType.PUBLIC\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version);\n}\n\nregisterAppCheck();\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppCheckError {\n USE_BEFORE_ACTIVATION = 'use-before-activation'\n}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\n [AppCheckError.USE_BEFORE_ACTIVATION]:\n 'App Check is being used before activate() is called for FirebaseApp {$appName}. ' +\n 'Call activate() before instantiating other Firebase services.'\n};\n\ninterface ErrorParams {\n [AppCheckError.USE_BEFORE_ACTIVATION]: { appName: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\n 'appCheck',\n 'AppCheck',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckProvider,\n AppCheckTokenResult,\n FirebaseAppCheck\n} from '@firebase/app-check-types';\nimport { _FirebaseService, FirebaseApp } from '@firebase/app-compat';\nimport {\n AppCheck as AppCheckServiceExp,\n CustomProvider,\n initializeAppCheck,\n ReCaptchaV3Provider,\n ReCaptchaEnterpriseProvider,\n setTokenAutoRefreshEnabled as setTokenAutoRefreshEnabledExp,\n getToken as getTokenExp,\n onTokenChanged as onTokenChangedExp\n} from '@firebase/app-check';\nimport { PartialObserver, Unsubscribe } from '@firebase/util';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\n\nexport class AppCheckService\n implements FirebaseAppCheck, Omit<_FirebaseService, '_delegate'>\n{\n _delegate?: AppCheckServiceExp;\n constructor(public app: FirebaseApp) {}\n\n activate(\n siteKeyOrProvider: string | AppCheckProvider,\n isTokenAutoRefreshEnabled?: boolean\n ): void {\n let provider:\n | ReCaptchaV3Provider\n | CustomProvider\n | ReCaptchaEnterpriseProvider;\n if (typeof siteKeyOrProvider === 'string') {\n provider = new ReCaptchaV3Provider(siteKeyOrProvider);\n } else if (\n siteKeyOrProvider instanceof ReCaptchaEnterpriseProvider ||\n siteKeyOrProvider instanceof ReCaptchaV3Provider ||\n siteKeyOrProvider instanceof CustomProvider\n ) {\n provider = siteKeyOrProvider;\n } else {\n provider = new CustomProvider({ getToken: siteKeyOrProvider.getToken });\n }\n this._delegate = initializeAppCheck(this.app, {\n provider,\n isTokenAutoRefreshEnabled\n });\n }\n\n setTokenAutoRefreshEnabled(isTokenAutoRefreshEnabled: boolean): void {\n if (!this._delegate) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: this.app.name\n });\n }\n setTokenAutoRefreshEnabledExp(this._delegate, isTokenAutoRefreshEnabled);\n }\n\n getToken(forceRefresh?: boolean): Promise<AppCheckTokenResult> {\n if (!this._delegate) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: this.app.name\n });\n }\n return getTokenExp(this._delegate, forceRefresh);\n }\n\n onTokenChanged(\n onNextOrObserver:\n | PartialObserver<AppCheckTokenResult>\n | ((tokenResult: AppCheckTokenResult) => void),\n onError?: (error: Error) => void,\n onCompletion?: () => void\n ): Unsubscribe {\n if (!this._delegate) {\n throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n appName: this.app.name\n });\n }\n return onTokenChangedExp(\n this._delegate,\n /**\n * Exp onTokenChanged() will handle both overloads but we need\n * to specify one to not confuse Typescript.\n */\n onNextOrObserver as (tokenResult: AppCheckTokenResult) => void,\n onError,\n onCompletion\n );\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, {\n _FirebaseNamespace,\n FirebaseApp\n} from '@firebase/app-compat';\nimport { name, version } from '../package.json';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport { AppCheckService } from './service';\nimport { FirebaseAppCheck } from '@firebase/app-check-types';\nimport {\n ReCaptchaV3Provider,\n ReCaptchaEnterpriseProvider,\n CustomProvider\n} from '@firebase/app-check';\n\nconst factory: InstanceFactory<'appCheck-compat'> = (\n container: ComponentContainer\n) => {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n\n return new AppCheckService(app as FirebaseApp);\n};\n\nexport function registerAppCheck(): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'appCheck-compat',\n factory,\n ComponentType.PUBLIC\n ).setServiceProps({\n ReCaptchaEnterpriseProvider,\n ReCaptchaV3Provider,\n CustomProvider\n })\n );\n}\n\nregisterAppCheck();\nfirebase.registerVersion(name, version);\n\n/**\n * Define extension behavior of `registerAppCheck`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n appCheck(app?: FirebaseApp): FirebaseAppCheck;\n }\n interface FirebaseApp {\n appCheck(): FirebaseAppCheck;\n }\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An enum of factors that may be used for multifactor authentication.\n *\n * @public\n */\nexport const FactorId = {\n /** Phone as second factor */\n PHONE: 'phone',\n TOTP: 'totp'\n} as const;\n\n/**\n * Enumeration of supported providers.\n *\n * @public\n */\nexport const ProviderId = {\n /** Facebook provider ID */\n FACEBOOK: 'facebook.com',\n /** GitHub provider ID */\n GITHUB: 'github.com',\n /** Google provider ID */\n GOOGLE: 'google.com',\n /** Password provider */\n PASSWORD: 'password',\n /** Phone provider */\n PHONE: 'phone',\n /** Twitter provider ID */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported sign-in methods.\n *\n * @public\n */\nexport const SignInMethod = {\n /** Email link sign in method */\n EMAIL_LINK: 'emailLink',\n /** Email/password sign in method */\n EMAIL_PASSWORD: 'password',\n /** Facebook sign in method */\n FACEBOOK: 'facebook.com',\n /** GitHub sign in method */\n GITHUB: 'github.com',\n /** Google sign in method */\n GOOGLE: 'google.com',\n /** Phone sign in method */\n PHONE: 'phone',\n /** Twitter sign in method */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported operation types.\n *\n * @public\n */\nexport const OperationType = {\n /** Operation involving linking an additional provider to an already signed-in user. */\n LINK: 'link',\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\n REAUTHENTICATE: 'reauthenticate',\n /** Operation involving signing in a user. */\n SIGN_IN: 'signIn'\n} as const;\n\n/**\n * An enumeration of the possible email action types.\n *\n * @public\n */\nexport const ActionCodeOperation = {\n /** The email link sign-in action. */\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n /** The password reset action. */\n PASSWORD_RESET: 'PASSWORD_RESET',\n /** The email revocation action. */\n RECOVER_EMAIL: 'RECOVER_EMAIL',\n /** The revert second factor addition email action. */\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\n /** The revert second factor addition email action. */\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n /** The email verification action. */\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n} as const;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorMap, User } from '../model/public_types';\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { AppName } from '../model/auth';\nimport { AuthCredential } from './credentials';\n\n/**\n * Enumeration of Firebase Auth error codes.\n *\n * @internal\n */\nexport const enum AuthErrorCode {\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 DEPENDENT_SDK_INIT_BEFORE_AUTH = 'dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',\n EMAIL_EXISTS = 'email-already-in-use',\n EMULATOR_CONFIG_FAILED = 'emulator-config-failed',\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_EMULATOR_SCHEME = 'invalid-emulator-scheme',\n INVALID_CREDENTIAL = 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD = 'invalid-message-payload',\n INVALID_MFA_SESSION = 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID = 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER = 'invalid-oauth-provider',\n INVALID_OOB_CODE = 'invalid-action-code',\n INVALID_ORIGIN = 'unauthorized-domain',\n INVALID_PASSWORD = 'wrong-password',\n INVALID_PERSISTENCE = 'invalid-persistence-type',\n INVALID_PHONE_NUMBER = 'invalid-phone-number',\n INVALID_PROVIDER_ID = 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL = 'invalid-recipient-email',\n INVALID_SENDER = 'invalid-sender',\n INVALID_SESSION_INFO = 'invalid-verification-id',\n INVALID_TENANT_ID = 'invalid-tenant-id',\n LOGIN_BLOCKED = 'login-blocked',\n MFA_INFO_NOT_FOUND = 'multi-factor-info-not-found',\n MFA_REQUIRED = 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME = 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL = 'missing-app-credential',\n MISSING_AUTH_DOMAIN = 'auth-domain-config-required',\n MISSING_CODE = 'missing-verification-code',\n MISSING_CONTINUE_URI = 'missing-continue-uri',\n MISSING_IFRAME_START = 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID = 'missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE = 'missing-or-invalid-nonce',\n MISSING_MFA_INFO = 'missing-multi-factor-info',\n MISSING_MFA_SESSION = 'missing-multi-factor-session',\n MISSING_PHONE_NUMBER = 'missing-phone-number',\n MISSING_PASSWORD = 'missing-password',\n MISSING_SESSION_INFO = 'missing-verification-id',\n MODULE_DESTROYED = 'app-deleted',\n NEED_CONFIRMATION = 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED = 'network-request-failed',\n NULL_USER = 'null-user',\n NO_AUTH_EVENT = 'no-auth-event',\n NO_SUCH_PROVIDER = 'no-such-provider',\n OPERATION_NOT_ALLOWED = 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED = 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED = 'popup-blocked',\n POPUP_CLOSED_BY_USER = 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED = 'provider-already-linked',\n QUOTA_EXCEEDED = 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER = 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING = 'redirect-operation-pending',\n REJECTED_CREDENTIAL = 'rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED = 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH = 'tenant-id-mismatch',\n TIMEOUT = 'timeout',\n TOKEN_EXPIRED = 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'too-many-requests',\n UNAUTHORIZED_DOMAIN = 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR = 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE = 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION = 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL = 'unverified-email',\n USER_CANCELLED = 'user-cancelled',\n USER_DELETED = 'user-not-found',\n USER_DISABLED = 'user-disabled',\n USER_MISMATCH = 'user-mismatch',\n USER_SIGNED_OUT = 'user-signed-out',\n WEAK_PASSWORD = 'weak-password',\n WEB_STORAGE_UNSUPPORTED = 'web-storage-unsupported',\n ALREADY_INITIALIZED = 'already-initialized',\n RECAPTCHA_NOT_ENABLED = 'recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN = 'missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN = 'invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION = 'invalid-recaptcha-action',\n MISSING_CLIENT_TYPE = 'missing-client-type',\n MISSING_RECAPTCHA_VERSION = 'missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION = 'invalid-recaptcha-version',\n INVALID_REQ_TYPE = 'invalid-req-type',\n UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION = 'unsupported-password-policy-schema-version',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'password-does-not-meet-requirements'\n}\n\nfunction _debugErrorMap(): ErrorMap<AuthErrorCode> {\n return {\n [AuthErrorCode.ADMIN_ONLY_OPERATION]:\n 'This operation is restricted to administrators only.',\n [AuthErrorCode.ARGUMENT_ERROR]: '',\n [AuthErrorCode.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.',\n [AuthErrorCode.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.',\n [AuthErrorCode.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.',\n [AuthErrorCode.CODE_EXPIRED]:\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [AuthErrorCode.CORDOVA_NOT_READY]: 'Cordova framework is not ready.',\n [AuthErrorCode.CORS_UNSUPPORTED]: 'This browser is not supported.',\n [AuthErrorCode.CREDENTIAL_ALREADY_IN_USE]:\n 'This credential is already associated with a different user account.',\n [AuthErrorCode.CREDENTIAL_MISMATCH]:\n 'The custom token corresponds to a different audience.',\n [AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED]:\n 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION]:\n 'Multi-factor users must always have a verified email.',\n [AuthErrorCode.EMAIL_EXISTS]:\n 'The email address is already in use by another account.',\n [AuthErrorCode.EMULATOR_CONFIG_FAILED]:\n 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',\n [AuthErrorCode.EXPIRED_POPUP_REQUEST]:\n 'This operation has been cancelled due to another conflicting popup being opened.',\n [AuthErrorCode.INTERNAL_ERROR]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_APP_CREDENTIAL]:\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [AuthErrorCode.INVALID_APP_ID]:\n 'The mobile app identifier is not registed for the current project.',\n [AuthErrorCode.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.',\n [AuthErrorCode.INVALID_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.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 to use the ' +\n 'verification code provided by the user.',\n [AuthErrorCode.INVALID_CONTINUE_URI]:\n 'The continue URL provided in the request is invalid.',\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]:\n 'The following 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.',\n [AuthErrorCode.INVALID_CUSTOM_TOKEN]:\n 'The custom token format is incorrect. Please check the documentation.',\n [AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN]:\n 'The provided dynamic link domain is not configured or authorized for the current project.',\n [AuthErrorCode.INVALID_EMAIL]: 'The email address is badly formatted.',\n [AuthErrorCode.INVALID_EMULATOR_SCHEME]:\n 'Emulator URL must start with a valid scheme (http:// or https://).',\n [AuthErrorCode.INVALID_API_KEY]:\n 'Your API key is invalid, please check you have copied it correctly.',\n [AuthErrorCode.INVALID_CERT_HASH]:\n 'The SHA-1 certificate hash provided is invalid.',\n [AuthErrorCode.INVALID_CREDENTIAL]:\n 'The supplied auth credential is incorrect, malformed or has expired.',\n [AuthErrorCode.INVALID_MESSAGE_PAYLOAD]:\n 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_MFA_SESSION]:\n 'The request does not contain a valid proof of first factor successful sign-in.',\n [AuthErrorCode.INVALID_OAUTH_PROVIDER]:\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [AuthErrorCode.INVALID_OAUTH_CLIENT_ID]:\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [AuthErrorCode.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.',\n [AuthErrorCode.INVALID_OOB_CODE]:\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [AuthErrorCode.INVALID_PASSWORD]:\n 'The password is invalid or the user does not have a password.',\n [AuthErrorCode.INVALID_PERSISTENCE]:\n 'The specified persistence type is invalid. It can only be local, session or none.',\n [AuthErrorCode.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].',\n [AuthErrorCode.INVALID_PROVIDER_ID]:\n 'The specified provider ID is invalid.',\n [AuthErrorCode.INVALID_RECIPIENT_EMAIL]:\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [AuthErrorCode.INVALID_SENDER]:\n 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_SESSION_INFO]:\n 'The verification ID used to create the phone auth credential is invalid.',\n [AuthErrorCode.INVALID_TENANT_ID]:\n \"The Auth instance's tenant ID is invalid.\",\n [AuthErrorCode.LOGIN_BLOCKED]:\n 'Login blocked by user-provided method: {$originalMessage}',\n [AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME]:\n 'An Android Package Name must be provided if the Android App is required to be installed.',\n [AuthErrorCode.MISSING_AUTH_DOMAIN]:\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [AuthErrorCode.MISSING_APP_CREDENTIAL]:\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [AuthErrorCode.MISSING_CODE]:\n 'The phone auth credential was created with an empty SMS verification code.',\n [AuthErrorCode.MISSING_CONTINUE_URI]:\n 'A continue URL must be provided in the request.',\n [AuthErrorCode.MISSING_IFRAME_START]: 'An internal AuthError has occurred.',\n [AuthErrorCode.MISSING_IOS_BUNDLE_ID]:\n 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [AuthErrorCode.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.',\n [AuthErrorCode.MISSING_PASSWORD]: 'A non-empty password must be provided',\n [AuthErrorCode.MISSING_MFA_INFO]:\n 'No second factor identifier is provided.',\n [AuthErrorCode.MISSING_MFA_SESSION]:\n 'The request is missing proof of first factor successful sign-in.',\n [AuthErrorCode.MISSING_PHONE_NUMBER]:\n 'To send verification codes, provide a phone number for the recipient.',\n [AuthErrorCode.MISSING_SESSION_INFO]:\n 'The phone auth credential was created with an empty verification ID.',\n [AuthErrorCode.MODULE_DESTROYED]:\n 'This instance of FirebaseApp has been deleted.',\n [AuthErrorCode.MFA_INFO_NOT_FOUND]:\n 'The user does not have a second factor matching the identifier provided.',\n [AuthErrorCode.MFA_REQUIRED]:\n 'Proof of ownership of a second factor is required to complete sign-in.',\n [AuthErrorCode.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.',\n [AuthErrorCode.NETWORK_REQUEST_FAILED]:\n 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [AuthErrorCode.NO_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.NO_SUCH_PROVIDER]:\n 'User was not linked to an account with the given provider.',\n [AuthErrorCode.NULL_USER]:\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [AuthErrorCode.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.',\n [AuthErrorCode.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.',\n [AuthErrorCode.POPUP_BLOCKED]:\n 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [AuthErrorCode.POPUP_CLOSED_BY_USER]:\n 'The popup has been closed by the user before finalizing the operation.',\n [AuthErrorCode.PROVIDER_ALREADY_LINKED]:\n 'User can only be linked to one identity for the given provider.',\n [AuthErrorCode.QUOTA_EXCEEDED]:\n \"The project's quota for this operation has been exceeded.\",\n [AuthErrorCode.REDIRECT_CANCELLED_BY_USER]:\n 'The redirect operation has been cancelled by the user before finalizing.',\n [AuthErrorCode.REDIRECT_OPERATION_PENDING]:\n 'A redirect sign-in operation is already pending.',\n [AuthErrorCode.REJECTED_CREDENTIAL]:\n 'The request contains malformed or mismatching credentials.',\n [AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED]:\n 'The second factor is already enrolled on this account.',\n [AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED]:\n 'The maximum allowed number of second factors on a user has been exceeded.',\n [AuthErrorCode.TENANT_ID_MISMATCH]:\n \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [AuthErrorCode.TIMEOUT]: 'The operation has timed out.',\n [AuthErrorCode.TOKEN_EXPIRED]:\n \"The user's credential is no longer valid. The user must sign in again.\",\n [AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER]:\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [AuthErrorCode.UNAUTHORIZED_DOMAIN]:\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\n [AuthErrorCode.UNSUPPORTED_FIRST_FACTOR]:\n 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\n [AuthErrorCode.UNSUPPORTED_PERSISTENCE]:\n 'The current environment does not support the specified persistence type.',\n [AuthErrorCode.UNSUPPORTED_TENANT_OPERATION]:\n 'This operation is not supported in a multi-tenant context.',\n [AuthErrorCode.UNVERIFIED_EMAIL]:\n 'The operation requires a verified email.',\n [AuthErrorCode.USER_CANCELLED]:\n 'The user did not grant your application the permissions it requested.',\n [AuthErrorCode.USER_DELETED]:\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [AuthErrorCode.USER_DISABLED]:\n 'The user account has been disabled by an administrator.',\n [AuthErrorCode.USER_MISMATCH]:\n 'The supplied credentials do not correspond to the previously signed in user.',\n [AuthErrorCode.USER_SIGNED_OUT]: '',\n [AuthErrorCode.WEAK_PASSWORD]:\n 'The password must be 6 characters long or more.',\n [AuthErrorCode.WEB_STORAGE_UNSUPPORTED]:\n 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [AuthErrorCode.ALREADY_INITIALIZED]:\n 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.',\n [AuthErrorCode.MISSING_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is invalid when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_ACTION]:\n 'The reCAPTCHA action is invalid when sending request to the backend.',\n [AuthErrorCode.RECAPTCHA_NOT_ENABLED]:\n 'reCAPTCHA Enterprise integration is not enabled for this project.',\n [AuthErrorCode.MISSING_CLIENT_TYPE]:\n 'The reCAPTCHA client type is missing when sending request to the backend.',\n [AuthErrorCode.MISSING_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_REQ_TYPE]: 'Invalid request parameters.',\n [AuthErrorCode.INVALID_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is invalid when sending request to the backend.',\n [AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION]:\n 'The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.',\n [AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n 'The password does not meet the requirements.'\n };\n}\n\nexport interface ErrorMapRetriever extends AuthErrorMap {\n (): ErrorMap<AuthErrorCode>;\n}\n\nfunction _prodErrorMap(): ErrorMap<AuthErrorCode> {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n } as ErrorMap<AuthErrorCode>;\n}\n\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const debugErrorMap: AuthErrorMap = _debugErrorMap;\n\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const prodErrorMap: AuthErrorMap = _prodErrorMap;\n\nexport interface NamedErrorParams {\n appName: AppName;\n credential?: AuthCredential;\n email?: string;\n phoneNumber?: string;\n tenantId?: string;\n user?: User;\n _serverResponse?: object;\n}\n\n/**\n * @internal\n */\ntype GenericAuthErrorParams = {\n [key in Exclude<\n AuthErrorCode,\n | AuthErrorCode.ARGUMENT_ERROR\n | AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n | AuthErrorCode.INTERNAL_ERROR\n | AuthErrorCode.MFA_REQUIRED\n | AuthErrorCode.NO_AUTH_EVENT\n | AuthErrorCode.OPERATION_NOT_SUPPORTED\n >]: {\n appName?: AppName;\n email?: string;\n phoneNumber?: string;\n message?: string;\n };\n};\n\n/**\n * @internal\n */\nexport interface AuthErrorParams extends GenericAuthErrorParams {\n [AuthErrorCode.ARGUMENT_ERROR]: { appName?: AppName };\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]: { appName?: AppName };\n [AuthErrorCode.INTERNAL_ERROR]: { appName?: AppName };\n [AuthErrorCode.LOGIN_BLOCKED]: {\n appName?: AppName;\n originalMessage?: string;\n };\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]: { appName?: AppName };\n [AuthErrorCode.NO_AUTH_EVENT]: { appName?: AppName };\n [AuthErrorCode.MFA_REQUIRED]: {\n appName: AppName;\n _serverResponse: IdTokenMfaResponse;\n };\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]: {\n appName: AppName;\n missingPlugin?: string;\n };\n}\n\nexport const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory<\n AuthErrorCode,\n AuthErrorParams\n>('auth', 'Firebase', _prodErrorMap());\n\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nexport const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_LOGIN_CREDENTIALS: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized',\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\n} as const;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '@firebase/app';\n\nexport { LogLevel };\n\nconst logClient = new Logger('@firebase/auth');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function _getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\nexport function _setLogLevel(newLevel: LogLevel): void {\n logClient.logLevel = newLevel;\n}\n\nexport function _logDebug(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n logClient.debug(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logWarn(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logError(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth } from '../../model/public_types';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../../model/auth';\nimport {\n _DEFAULT_AUTH_ERROR_FACTORY,\n AuthErrorCode,\n AuthErrorParams,\n prodErrorMap,\n ErrorMapRetriever\n} from '../errors';\nimport { _logError } from './log';\n\ntype AuthErrorListParams<K> = K extends keyof AuthErrorParams\n ? [AuthErrorParams[K]]\n : [];\ntype LessAppName<K extends AuthErrorCode> = Omit<AuthErrorParams[K], 'appName'>;\n\n/**\n * Unconditionally fails, throwing a developer facing INTERNAL_ERROR\n *\n * @example\n * ```javascript\n * fail(auth, AuthErrorCode.MFA_REQUIRED); // Error: the MFA_REQUIRED error needs more params than appName\n * fail(auth, AuthErrorCode.MFA_REQUIRED, {serverResponse}); // Compiles\n * fail(AuthErrorCode.INTERNAL_ERROR); // Compiles; internal error does not need appName\n * fail(AuthErrorCode.USER_DELETED); // Error: USER_DELETED requires app name\n * fail(auth, AuthErrorCode.USER_DELETED); // Compiles; USER_DELETED _only_ needs app name\n * ```\n *\n * @param appName App name for tagging the error\n * @throws FirebaseError\n */\nexport function _fail<K extends AuthErrorCode>(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): never;\nexport function _fail<K extends AuthErrorCode>(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): never;\nexport function _fail<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): never {\n throw createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _createError<K extends AuthErrorCode>(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): FirebaseError;\nexport function _createError<K extends AuthErrorCode>(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): FirebaseError;\nexport function _createError<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n return createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _errorWithCustomMessage(\n auth: Auth,\n code: AuthErrorCode,\n message: string\n): FirebaseError {\n const errorMap = {\n ...(prodErrorMap as ErrorMapRetriever)(),\n [code]: message\n };\n const factory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(\n 'auth',\n 'Firebase',\n errorMap\n );\n return factory.create(code, {\n appName: auth.name\n });\n}\n\nexport function _assertInstanceOf(\n auth: Auth,\n object: object,\n instance: unknown\n): void {\n const constructorInstance = instance as { new (...args: unknown[]): unknown };\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, AuthErrorCode.ARGUMENT_ERROR);\n }\n\n throw _errorWithCustomMessage(\n auth,\n AuthErrorCode.ARGUMENT_ERROR,\n `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`\n );\n }\n}\n\nfunction createErrorInternal<K extends AuthErrorCode>(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n if (typeof authOrCode !== 'string') {\n const code = rest[0] as K;\n const fullParams = [...rest.slice(1)] as AuthErrorListParams<K>;\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n\n return (authOrCode as AuthInternal)._errorFactory.create(\n code,\n ...fullParams\n );\n }\n\n return _DEFAULT_AUTH_ERROR_FACTORY.create(\n authOrCode,\n ...(rest as AuthErrorListParams<K>)\n );\n}\n\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): asserts assertion;\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName<K> ? [LessAppName<K>?] : [LessAppName<K>]\n): asserts assertion;\nexport function _assert<K extends AuthErrorCode>(\n assertion: unknown,\n authOrCode: Auth | K,\n ...rest: unknown[]\n): asserts assertion {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n\n// We really do want to accept literally any function type here\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype TypeExpectation = Function | string | MapType;\n\ninterface MapType extends Record<string, TypeExpectation | Optional> {}\n\nclass Optional {\n constructor(readonly type: TypeExpectation) {}\n}\n\nexport function opt(type: TypeExpectation): Optional {\n return new Optional(type);\n}\n\n/**\n * Asserts the runtime types of arguments. The 'expected' field can be one of\n * a class, a string (representing a \"typeof\" call), or a record map of name\n * to type. Furthermore, the opt() function can be used to mark a field as\n * optional. For example:\n *\n * function foo(auth: Auth, profile: {displayName?: string}, update = false) {\n * assertTypes(arguments, [AuthImpl, {displayName: opt('string')}, opt('boolean')]);\n * }\n *\n * opt() can be used for any type:\n * function foo(auth?: Auth) {\n * assertTypes(arguments, [opt(AuthImpl)]);\n * }\n *\n * The string types can be or'd together, and you can use \"null\" as well (note\n * that typeof null === 'object'; this is an edge case). For example:\n *\n * function foo(profile: {displayName?: string | null}) {\n * assertTypes(arguments, [{displayName: opt('string|null')}]);\n * }\n *\n * @param args\n * @param expected\n */\nexport function assertTypes(\n args: Omit<IArguments, 'callee'>,\n ...expected: Array<TypeExpectation | Optional>\n): void {\n if (args.length > expected.length) {\n _fail(AuthErrorCode.ARGUMENT_ERROR, {});\n }\n\n for (let i = 0; i < expected.length; i++) {\n let expect = expected[i];\n const arg = args[i];\n\n if (expect instanceof Optional) {\n // If the arg is undefined, then it matches \"optional\" and we can move to\n // the next arg\n if (typeof arg === 'undefined') {\n continue;\n }\n expect = expect.type;\n }\n\n if (typeof expect === 'string') {\n // Handle the edge case for null because typeof null === 'object'\n if (expect.includes('null') && arg === null) {\n continue;\n }\n\n const required = expect.split('|');\n _assert(required.includes(typeof arg), AuthErrorCode.ARGUMENT_ERROR, {});\n } else if (typeof expect === 'object') {\n // Recursively check record arguments\n const record = arg as Record<string, unknown>;\n const map = expect as MapType;\n const keys = Object.keys(expect);\n\n assertTypes(\n keys.map(k => record[k]),\n ...keys.map(k => map[k])\n );\n } else {\n _assert(arg instanceof expect, AuthErrorCode.ARGUMENT_ERROR, {});\n }\n }\n}\n\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nexport function debugFail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n\n // NOTE: We don't use FirebaseError 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 *\n * @param assertion\n * @param message\n */\nexport function debugAssert(\n assertion: unknown,\n message: string\n): asserts assertion {\n if (!assertion) {\n debugFail(message);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _getCurrentUrl(): string {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\n\nexport function _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\nexport function _getCurrentScheme(): string | null {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isMobileCordova, isReactNative } from '@firebase/util';\nimport { _isOnline } from './navigator';\nimport { debugAssert } from './assert';\n\nexport const enum DelayMin {\n OFFLINE = 5000\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 */\nexport class Delay {\n // The default value for the offline delay timeout in ms.\n\n private readonly isMobile: boolean;\n constructor(\n private readonly shortDelay: number,\n private readonly longDelay: number\n ) {\n // Internal error when improperly initialized.\n debugAssert(\n longDelay > shortDelay,\n 'Short delay should be less than long delay!'\n );\n this.isMobile = isMobileCordova() || isReactNative();\n }\n\n get(): number {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(DelayMin.OFFLINE, 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 * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isBrowserExtension } from '@firebase/util';\nimport { _isHttpOrHttps } from './location';\n\n/**\n * Determine whether the browser is working online\n */\nexport function _isOnline(): boolean {\n if (\n typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in 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 (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)\n ) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\n\nexport function _getUserLanguage(): string | null {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage: NavigatorLanguage = navigator;\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 // Couldn't determine language.\n null\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigInternal } from '../../model/auth';\nimport { debugAssert } from './assert';\n\nexport function _emulatorUrl(config: ConfigInternal, path?: string): string {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n\n if (!path) {\n return url;\n }\n\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugFail } from './assert';\n\nexport class FetchProvider {\n private static fetchImpl: typeof fetch | null;\n private static headersImpl: typeof Headers | null;\n private static responseImpl: typeof Response | null;\n\n static initialize(\n fetchImpl: typeof fetch,\n headersImpl?: typeof Headers,\n responseImpl?: typeof Response\n ): void {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n\n static fetch(): typeof fetch {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\n return globalThis.fetch;\n }\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n debugFail(\n 'Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static headers(): typeof Headers {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\n return globalThis.Headers;\n }\n if (typeof Headers !== 'undefined') {\n return Headers;\n }\n debugFail(\n 'Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static response(): typeof Response {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\n return globalThis.Response;\n }\n if (typeof Response !== 'undefined') {\n return Response;\n }\n debugFail(\n 'Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\n\n/**\n * Errors that can be returned by the backend\n */\nexport const enum ServerError {\n ADMIN_ONLY_OPERATION = 'ADMIN_ONLY_OPERATION',\n BLOCKING_FUNCTION_ERROR_RESPONSE = 'BLOCKING_FUNCTION_ERROR_RESPONSE',\n CAPTCHA_CHECK_FAILED = 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED = 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH = 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED = 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS = 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND = 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE = 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED = 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL = 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID = 'INVALID_APP_ID',\n INVALID_CERT_HASH = 'INVALID_CERT_HASH',\n INVALID_CODE = 'INVALID_CODE',\n INVALID_CONTINUE_URI = 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN = 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN = 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL = 'INVALID_EMAIL',\n INVALID_ID_TOKEN = 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE = 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER = 'INVALID_IDENTIFIER',\n INVALID_LOGIN_CREDENTIALS = 'INVALID_LOGIN_CREDENTIALS',\n INVALID_MESSAGE_PAYLOAD = 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL = 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID = 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE = 'INVALID_OOB_CODE',\n INVALID_PASSWORD = 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN = 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER = 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID = 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL = 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER = 'INVALID_SENDER',\n INVALID_SESSION_INFO = 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF = 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID = 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND = 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME = 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL = 'MISSING_APP_CREDENTIAL',\n MISSING_CODE = 'MISSING_CODE',\n MISSING_CONTINUE_URI = 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN = 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID = 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID = 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL = 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE = 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE = 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD = 'MISSING_PASSWORD',\n MISSING_REQ_TYPE = 'MISSING_REQ_TYPE',\n MISSING_PHONE_NUMBER = 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO = 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT = 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL = 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS = 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH = 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR = 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION = 'UNSUPPORTED_TENANT_OPERATION',\n UNAUTHORIZED_DOMAIN = 'UNAUTHORIZED_DOMAIN',\n UNVERIFIED_EMAIL = 'UNVERIFIED_EMAIL',\n USER_CANCELLED = 'USER_CANCELLED',\n USER_DISABLED = 'USER_DISABLED',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n RECAPTCHA_NOT_ENABLED = 'RECAPTCHA_NOT_ENABLED',\n MISSING_RECAPTCHA_TOKEN = 'MISSING_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_TOKEN = 'INVALID_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_ACTION = 'INVALID_RECAPTCHA_ACTION',\n MISSING_CLIENT_TYPE = 'MISSING_CLIENT_TYPE',\n MISSING_RECAPTCHA_VERSION = 'MISSING_RECAPTCHA_VERSION',\n INVALID_RECAPTCHA_VERSION = 'INVALID_RECAPTCHA_VERSION',\n INVALID_REQ_TYPE = 'INVALID_REQ_TYPE',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'PASSWORD_DOES_NOT_MEET_REQUIREMENTS'\n}\n\n/**\n * API Response in the event of an error\n */\nexport interface JsonError {\n error: {\n code: number;\n message: string;\n errors?: [\n {\n message: ServerError;\n domain: string;\n reason: string;\n }\n ];\n };\n}\n\n/**\n * Type definition for a map from server errors to developer visible errors\n */\nexport declare type ServerErrorMap<ApiError extends string> = {\n readonly [K in ApiError]: AuthErrorCode;\n};\n\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nexport const SERVER_ERROR_MAP: Partial<ServerErrorMap<ServerError>> = {\n // Custom token errors.\n [ServerError.CREDENTIAL_MISMATCH]: AuthErrorCode.CREDENTIAL_MISMATCH,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CUSTOM_TOKEN]: AuthErrorCode.INTERNAL_ERROR,\n\n // Create Auth URI errors.\n [ServerError.INVALID_IDENTIFIER]: AuthErrorCode.INVALID_EMAIL,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CONTINUE_URI]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign in with email and password errors (some apply to sign up too).\n [ServerError.INVALID_PASSWORD]: AuthErrorCode.INVALID_PASSWORD,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_PASSWORD]: AuthErrorCode.MISSING_PASSWORD,\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\n // invalid.\n [ServerError.INVALID_LOGIN_CREDENTIALS]: AuthErrorCode.INVALID_CREDENTIAL,\n\n // Sign up with email and password errors.\n [ServerError.EMAIL_EXISTS]: AuthErrorCode.EMAIL_EXISTS,\n [ServerError.PASSWORD_LOGIN_DISABLED]: AuthErrorCode.OPERATION_NOT_ALLOWED,\n\n // Verify assertion for sign in with credential errors:\n [ServerError.INVALID_IDP_RESPONSE]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.INVALID_PENDING_TOKEN]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.FEDERATED_USER_ID_ALREADY_LINKED]:\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_REQ_TYPE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Send Password reset email errors:\n [ServerError.EMAIL_NOT_FOUND]: AuthErrorCode.USER_DELETED,\n [ServerError.RESET_PASSWORD_EXCEED_LIMIT]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n [ServerError.EXPIRED_OOB_CODE]: AuthErrorCode.EXPIRED_OOB_CODE,\n [ServerError.INVALID_OOB_CODE]: AuthErrorCode.INVALID_OOB_CODE,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_OOB_CODE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Operations that require ID token in request:\n [ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,\n [ServerError.INVALID_ID_TOKEN]: AuthErrorCode.INVALID_AUTH,\n [ServerError.TOKEN_EXPIRED]: AuthErrorCode.TOKEN_EXPIRED,\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.TOKEN_EXPIRED,\n\n // Other errors.\n [ServerError.TOO_MANY_ATTEMPTS_TRY_LATER]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n [ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS,\n\n // Phone Auth related errors.\n [ServerError.INVALID_CODE]: AuthErrorCode.INVALID_CODE,\n [ServerError.INVALID_SESSION_INFO]: AuthErrorCode.INVALID_SESSION_INFO,\n [ServerError.INVALID_TEMPORARY_PROOF]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.MISSING_SESSION_INFO]: AuthErrorCode.MISSING_SESSION_INFO,\n [ServerError.SESSION_EXPIRED]: AuthErrorCode.CODE_EXPIRED,\n\n // Other action code errors when additional settings passed.\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 [ServerError.MISSING_ANDROID_PACKAGE_NAME]:\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME,\n [ServerError.UNAUTHORIZED_DOMAIN]: AuthErrorCode.UNAUTHORIZED_DOMAIN,\n\n // getProjectConfig errors when clientId is passed.\n [ServerError.INVALID_OAUTH_CLIENT_ID]: AuthErrorCode.INVALID_OAUTH_CLIENT_ID,\n\n // User actions (sign-up or deletion) disabled errors.\n [ServerError.ADMIN_ONLY_OPERATION]: AuthErrorCode.ADMIN_ONLY_OPERATION,\n\n // Multi factor related errors.\n [ServerError.INVALID_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.INVALID_MFA_SESSION,\n [ServerError.MFA_ENROLLMENT_NOT_FOUND]: AuthErrorCode.MFA_INFO_NOT_FOUND,\n [ServerError.MISSING_MFA_ENROLLMENT_ID]: AuthErrorCode.MISSING_MFA_INFO,\n [ServerError.MISSING_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.MISSING_MFA_SESSION,\n [ServerError.SECOND_FACTOR_EXISTS]:\n AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED,\n [ServerError.SECOND_FACTOR_LIMIT_EXCEEDED]:\n AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED,\n\n // Blocking functions related errors.\n [ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Recaptcha related errors.\n [ServerError.RECAPTCHA_NOT_ENABLED]: AuthErrorCode.RECAPTCHA_NOT_ENABLED,\n [ServerError.MISSING_RECAPTCHA_TOKEN]: AuthErrorCode.MISSING_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_TOKEN]: AuthErrorCode.INVALID_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_ACTION]:\n AuthErrorCode.INVALID_RECAPTCHA_ACTION,\n [ServerError.MISSING_CLIENT_TYPE]: AuthErrorCode.MISSING_CLIENT_TYPE,\n [ServerError.MISSING_RECAPTCHA_VERSION]:\n AuthErrorCode.MISSING_RECAPTCHA_VERSION,\n [ServerError.INVALID_RECAPTCHA_VERSION]:\n AuthErrorCode.INVALID_RECAPTCHA_VERSION,\n [ServerError.INVALID_REQ_TYPE]: AuthErrorCode.INVALID_REQ_TYPE\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError, querystring } from '@firebase/util';\n\nimport { AuthErrorCode, NamedErrorParams } from '../core/errors';\nimport {\n _createError,\n _errorWithCustomMessage,\n _fail\n} from '../core/util/assert';\nimport { Delay } from '../core/util/delay';\nimport { _emulatorUrl } from '../core/util/emulator';\nimport { FetchProvider } from '../core/util/fetch_provider';\nimport { Auth } from '../model/public_types';\nimport { AuthInternal, ConfigInternal } from '../model/auth';\nimport { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';\nimport { IdTokenMfaResponse } from './authentication/mfa';\nimport { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';\n\nexport const enum HttpMethod {\n POST = 'POST',\n GET = 'GET'\n}\n\nexport const enum HttpHeader {\n CONTENT_TYPE = 'Content-Type',\n X_FIREBASE_LOCALE = 'X-Firebase-Locale',\n X_CLIENT_VERSION = 'X-Client-Version',\n X_FIREBASE_GMPID = 'X-Firebase-gmpid',\n X_FIREBASE_CLIENT = 'X-Firebase-Client',\n X_FIREBASE_APP_CHECK = 'X-Firebase-AppCheck'\n}\n\nexport const enum Endpoint {\n CREATE_AUTH_URI = '/v1/accounts:createAuthUri',\n DELETE_ACCOUNT = '/v1/accounts:delete',\n RESET_PASSWORD = '/v1/accounts:resetPassword',\n SIGN_UP = '/v1/accounts:signUp',\n SIGN_IN_WITH_CUSTOM_TOKEN = '/v1/accounts:signInWithCustomToken',\n SIGN_IN_WITH_EMAIL_LINK = '/v1/accounts:signInWithEmailLink',\n SIGN_IN_WITH_IDP = '/v1/accounts:signInWithIdp',\n SIGN_IN_WITH_PASSWORD = '/v1/accounts:signInWithPassword',\n SIGN_IN_WITH_PHONE_NUMBER = '/v1/accounts:signInWithPhoneNumber',\n SEND_VERIFICATION_CODE = '/v1/accounts:sendVerificationCode',\n SEND_OOB_CODE = '/v1/accounts:sendOobCode',\n SET_ACCOUNT_INFO = '/v1/accounts:update',\n GET_ACCOUNT_INFO = '/v1/accounts:lookup',\n GET_RECAPTCHA_PARAM = '/v1/recaptchaParams',\n START_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:start',\n FINALIZE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',\n START_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',\n FINALIZE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',\n WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',\n GET_PROJECT_CONFIG = '/v1/projects',\n GET_RECAPTCHA_CONFIG = '/v2/recaptchaConfig',\n GET_PASSWORD_POLICY = '/v2/passwordPolicy',\n TOKEN = '/v1/token',\n REVOKE_TOKEN = '/v2/accounts:revokeToken'\n}\n\nexport const enum RecaptchaClientType {\n WEB = 'CLIENT_TYPE_WEB',\n ANDROID = 'CLIENT_TYPE_ANDROID',\n IOS = 'CLIENT_TYPE_IOS'\n}\n\nexport const enum RecaptchaVersion {\n ENTERPRISE = 'RECAPTCHA_ENTERPRISE'\n}\n\nexport const enum RecaptchaActionName {\n SIGN_IN_WITH_PASSWORD = 'signInWithPassword',\n GET_OOB_CODE = 'getOobCode',\n SIGN_UP_PASSWORD = 'signUpPassword'\n}\n\nexport const enum EnforcementState {\n ENFORCE = 'ENFORCE',\n AUDIT = 'AUDIT',\n OFF = 'OFF',\n ENFORCEMENT_STATE_UNSPECIFIED = 'ENFORCEMENT_STATE_UNSPECIFIED'\n}\n\n// Providers that have reCAPTCHA Enterprise support.\nexport const enum RecaptchaProvider {\n EMAIL_PASSWORD_PROVIDER = 'EMAIL_PASSWORD_PROVIDER'\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);\n\nexport function _addTidIfNecessary<T extends { tenantId?: string }>(\n auth: Auth,\n request: T\n): T {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\n\nexport async function _performApiRequest<T, V>(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial<ServerErrorMap<ServerError>> = {}\n): Promise<V> {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === HttpMethod.GET) {\n params = request;\n } else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n\n const query = querystring({\n key: auth.config.apiKey,\n ...params\n }).slice(1);\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/json';\n\n if (auth.languageCode) {\n headers[HttpHeader.X_FIREBASE_LOCALE] = auth.languageCode;\n }\n\n return FetchProvider.fetch()(\n _getFinalTarget(auth, auth.config.apiHost, path, query),\n {\n method,\n headers,\n referrerPolicy: 'no-referrer',\n ...body\n }\n );\n });\n}\n\nexport async function _performFetchWithErrorHandling<V>(\n auth: Auth,\n customErrorMap: Partial<ServerErrorMap<ServerError>>,\n fetchFn: () => Promise<Response>\n): Promise<V> {\n (auth as AuthInternal)._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout<Response>(auth);\n const response: Response = await Promise.race<Promise<Response>>([\n fetchFn(),\n networkTimeout.promise\n ]);\n\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, json);\n }\n\n if (response.ok && !('errorMessage' in json)) {\n return json;\n } else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n throw _makeTaggedError(\n auth,\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n json\n );\n } else if (serverErrorCode === ServerError.EMAIL_EXISTS) {\n throw _makeTaggedError(auth, AuthErrorCode.EMAIL_EXISTS, json);\n } else if (serverErrorCode === ServerError.USER_DISABLED) {\n throw _makeTaggedError(auth, AuthErrorCode.USER_DISABLED, json);\n }\n const authError =\n errorMap[serverErrorCode as ServerError] ||\n (serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-') as unknown as AuthErrorCode);\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n } else {\n _fail(auth, authError);\n }\n }\n } catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n // Changing this to a different error code will log user out when there is a network error\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\n _fail(auth, AuthErrorCode.NETWORK_REQUEST_FAILED, { 'message': String(e) });\n }\n}\n\nexport async function _performSignInRequest<T, V extends IdTokenResponse>(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial<ServerErrorMap<ServerError>> = {}\n): Promise<V> {\n const serverResponse = (await _performApiRequest<T, V | IdTokenMfaResponse>(\n auth,\n method,\n path,\n request,\n customErrorMap\n )) as V;\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, AuthErrorCode.MFA_REQUIRED, {\n _serverResponse: serverResponse\n });\n }\n\n return serverResponse;\n}\n\nexport function _getFinalTarget(\n auth: Auth,\n host: string,\n path: string,\n query: string\n): string {\n const base = `${host}${path}?${query}`;\n\n if (!(auth as AuthInternal).config.emulator) {\n return `${auth.config.apiScheme}://${base}`;\n }\n\n return _emulatorUrl(auth.config as ConfigInternal, base);\n}\n\nexport function _parseEnforcementState(\n enforcementStateStr: string\n): EnforcementState {\n switch (enforcementStateStr) {\n case 'ENFORCE':\n return EnforcementState.ENFORCE;\n case 'AUDIT':\n return EnforcementState.AUDIT;\n case 'OFF':\n return EnforcementState.OFF;\n default:\n return EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED;\n }\n}\n\nclass NetworkTimeout<T> {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timer: any | null = null;\n readonly promise = new Promise<T>((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(\n _createError(this.auth, AuthErrorCode.NETWORK_REQUEST_FAILED)\n );\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n\n clearNetworkTimeout(): void {\n clearTimeout(this.timer);\n }\n\n constructor(private readonly auth: Auth) {}\n}\n\ninterface PotentialResponse extends IdTokenResponse {\n email?: string;\n phoneNumber?: string;\n}\n\nexport function _makeTaggedError(\n auth: Auth,\n code: AuthErrorCode,\n response: PotentialResponse\n): FirebaseError {\n const errorParams: NamedErrorParams = {\n appName: auth.name\n };\n\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n\n const error = _createError(auth, code, errorParams);\n\n // We know customData is defined on error because errorParams is defined\n (error.customData! as TaggedWithTokenResponse)._tokenResponse = response;\n return error;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RecaptchaParameters } from '../../model/public_types';\nimport {\n GetRecaptchaConfigResponse,\n RecaptchaEnforcementProviderState\n} from '../../api/authentication/recaptcha';\nimport { EnforcementState, _parseEnforcementState } from '../../api/index';\n\n// reCAPTCHA v2 interface\nexport interface Recaptcha {\n render: (container: HTMLElement, parameters: RecaptchaParameters) => number;\n getResponse: (id: number) => string;\n execute: (id: number) => unknown;\n reset: (id: number) => unknown;\n}\n\nexport function isV2(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is Recaptcha {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as Recaptcha).getResponse !== undefined\n );\n}\n\n// reCAPTCHA Enterprise & v3 shared interface\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\n// reCAPTCHA Enterprise interface\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise<string>;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n}\n\nexport function isEnterprise(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is GreCAPTCHATopLevel {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as GreCAPTCHATopLevel).enterprise !== undefined\n );\n}\n\n// TODO(chuanr): Replace this with the AuthWindow after resolving the dependency issue in Node.js env.\ndeclare global {\n interface Window {\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n }\n}\n\nexport class RecaptchaConfig {\n /**\n * The reCAPTCHA site key.\n */\n siteKey: string = '';\n\n /**\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\n */\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[] = [];\n\n constructor(response: GetRecaptchaConfigResponse) {\n if (response.recaptchaKey === undefined) {\n throw new Error('recaptchaKey undefined');\n }\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\n this.siteKey = response.recaptchaKey.split('/')[3];\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\n }\n\n /**\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\n *\n * @param providerStr - The provider whose enforcement state is to be returned.\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\n */\n getProviderEnforcementState(providerStr: string): EnforcementState | null {\n if (\n !this.recaptchaEnforcementState ||\n this.recaptchaEnforcementState.length === 0\n ) {\n return null;\n }\n\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\n if (\n recaptchaEnforcementState.provider &&\n recaptchaEnforcementState.provider === providerStr\n ) {\n return _parseEnforcementState(\n recaptchaEnforcementState.enforcementState\n );\n }\n }\n return null;\n }\n\n /**\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\n *\n * @param providerStr - The provider whose enablement state is to be returned.\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\n */\n isProviderEnabled(providerStr: string): boolean {\n return (\n this.getProviderEnforcementState(providerStr) ===\n EnforcementState.ENFORCE ||\n this.getProviderEnforcementState(providerStr) === EnforcementState.AUDIT\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function utcTimestampToDateString(\n utcTimestamp?: string | number\n): string | undefined {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult, ParsedToken, User } from '../../model/public_types';\nimport { base64Decode, getModularInstance } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { _logError } from '../util/log';\nimport { utcTimestampToDateString } from '../util/time';\nimport { AuthErrorCode } from '../errors';\n\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport function getIdToken(user: User, forceRefresh = false): Promise<string> {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getIdTokenResult(\n user: User,\n forceRefresh = false\n): Promise<IdTokenResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n\n _assert(\n claims && claims.exp && claims.auth_time && claims.iat,\n userInternal.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const firebase =\n typeof claims.firebase === 'object' ? claims.firebase : undefined;\n\n const signInProvider: string | undefined = firebase?.['sign_in_provider'];\n\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.auth_time)\n )!,\n issuedAtTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.iat)\n )!,\n expirationTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.exp)\n )!,\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\n\nfunction secondsStringToMilliseconds(seconds: string): number {\n return Number(seconds) * 1000;\n}\n\nexport function _parseToken(token: string): ParsedToken | null {\n const [algorithm, payload, signature] = token.split('.');\n if (\n algorithm === undefined ||\n payload === undefined ||\n signature === undefined\n ) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n } catch (e) {\n _logError(\n 'Caught error parsing JWT payload as JSON',\n (e as Error)?.toString()\n );\n return null;\n }\n}\n\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nexport function _tokenExpiresIn(token: string): number {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.exp !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.iat !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\nexport async function _logoutIfInvalidated<T>(\n user: UserInternal,\n promise: Promise<T>,\n bypassAuthState = false\n): Promise<T> {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n } catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n\n throw e;\n }\n}\n\nfunction isUserInvalidated({ code }: FirebaseError): boolean {\n return (\n code === `auth/${AuthErrorCode.USER_DISABLED}` ||\n code === `auth/${AuthErrorCode.TOKEN_EXPIRED}`\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\n// Refresh the token five minutes before expiration\nexport const enum Duration {\n OFFSET = 5 * 1000 * 60,\n RETRY_BACKOFF_MIN = 30 * 1000,\n RETRY_BACKOFF_MAX = 16 * 60 * 1000\n}\n\nexport class ProactiveRefresh {\n private isRunning = false;\n\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timerId: any | null = null;\n private errorBackoff = Duration.RETRY_BACKOFF_MIN;\n\n constructor(private readonly user: UserInternal) {}\n\n _start(): void {\n if (this.isRunning) {\n return;\n }\n\n this.isRunning = true;\n this.schedule();\n }\n\n _stop(): void {\n if (!this.isRunning) {\n return;\n }\n\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n\n private getInterval(wasError: boolean): number {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(\n this.errorBackoff * 2,\n Duration.RETRY_BACKOFF_MAX\n );\n return interval;\n } else {\n // Reset the error backoff\n this.errorBackoff = Duration.RETRY_BACKOFF_MIN;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - Duration.OFFSET;\n\n return Math.max(0, interval);\n }\n }\n\n private schedule(wasError = false): void {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n\n private async iteration(): Promise<void> {\n try {\n await this.user.getIdToken(true);\n } catch (e) {\n // Only retry on network errors\n if (\n (e as FirebaseError)?.code ===\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n this.schedule(/* wasError */ true);\n }\n\n return;\n }\n this.schedule();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserMetadata as UserMetadataType } from '../../model/public_types';\n\nimport { utcTimestampToDateString } from '../util/time';\n\nexport class UserMetadata implements UserMetadataType {\n creationTime?: string;\n lastSignInTime?: string;\n\n constructor(\n private createdAt?: string | number,\n private lastLoginAt?: string | number\n ) {\n this._initializeTime();\n }\n\n private _initializeTime(): void {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n\n _copy(metadata: UserMetadata): void {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n\n toJSON(): object {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\n };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User, UserInfo } from '../../model/public_types';\n\nimport {\n getAccountInfo,\n ProviderUserInfo\n} from '../../api/account_management/account';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserMetadata } from './user_metadata';\nimport { getModularInstance } from '@firebase/util';\n\nexport async function _reloadWithoutSaving(user: UserInternal): Promise<void> {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(\n user,\n getAccountInfo(auth, { idToken })\n );\n\n _assert(response?.users.length, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const coreAccount = response.users[0];\n\n user._notifyReloadListener(coreAccount);\n\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const providerData = mergeProviderData(user.providerData, newProviderData);\n\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous =\n !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n\n const updates: Partial<UserInternal> = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n\n Object.assign(user, updates);\n}\n\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function reload(user: User): Promise<void> {\n const userInternal: UserInternal = getModularInstance(user) as UserInternal;\n await _reloadWithoutSaving(userInternal);\n\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\n\nfunction mergeProviderData(\n original: UserInfo[],\n newData: UserInfo[]\n): UserInfo[] {\n const deduped = original.filter(\n o => !newData.some(n => n.providerId === o.providerId)\n );\n return [...deduped, ...newData];\n}\n\nfunction extractProviderData(providers: ProviderUserInfo[]): UserInfo[] {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\n };\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { MfaEnrollment } from './mfa';\nimport { Auth } from '../../model/public_types';\n\nexport interface DeleteAccountRequest {\n idToken: string;\n}\n\nexport async function deleteAccount(\n auth: Auth,\n request: DeleteAccountRequest\n): Promise<void> {\n return _performApiRequest<DeleteAccountRequest, void>(\n auth,\n HttpMethod.POST,\n Endpoint.DELETE_ACCOUNT,\n request\n );\n}\n\nexport interface ProviderUserInfo {\n providerId: string;\n rawId?: string;\n email?: string;\n displayName?: string;\n photoUrl?: string;\n phoneNumber?: string;\n}\n\nexport interface DeleteLinkedAccountsRequest {\n idToken: string;\n deleteProvider: string[];\n}\n\nexport interface DeleteLinkedAccountsResponse {\n providerUserInfo: ProviderUserInfo[];\n}\n\nexport async function deleteLinkedAccounts(\n auth: Auth,\n request: DeleteLinkedAccountsRequest\n): Promise<DeleteLinkedAccountsResponse> {\n return _performApiRequest<\n DeleteLinkedAccountsRequest,\n DeleteLinkedAccountsResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface APIUserInfo {\n localId?: string;\n displayName?: string;\n photoUrl?: string;\n email?: string;\n emailVerified?: boolean;\n phoneNumber?: string;\n lastLoginAt?: number;\n createdAt?: number;\n tenantId?: string;\n passwordHash?: string;\n providerUserInfo?: ProviderUserInfo[];\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface GetAccountInfoRequest {\n idToken: string;\n}\n\nexport interface GetAccountInfoResponse {\n users: APIUserInfo[];\n}\n\nexport async function getAccountInfo(\n auth: Auth,\n request: GetAccountInfoRequest\n): Promise<GetAccountInfoResponse> {\n return _performApiRequest<GetAccountInfoRequest, GetAccountInfoResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.GET_ACCOUNT_INFO,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { requestStsToken } from '../../api/authentication/token';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert, debugFail } from '../util/assert';\nimport { _tokenExpiresIn } from './id_token_result';\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 */\nexport const enum Buffer {\n TOKEN_REFRESH = 30_000\n}\n\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport class StsTokenManager {\n refreshToken: string | null = null;\n accessToken: string | null = null;\n expirationTime: number | null = null;\n\n get isExpired(): boolean {\n return (\n !this.expirationTime ||\n Date.now() > this.expirationTime - Buffer.TOKEN_REFRESH\n );\n }\n\n updateFromServerResponse(\n response: IdTokenResponse | FinalizeMfaResponse\n ): void {\n _assert(response.idToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(\n typeof response.idToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof response.refreshToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const expiresIn =\n 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(\n response.idToken,\n response.refreshToken,\n expiresIn\n );\n }\n\n async getToken(\n auth: AuthInternal,\n forceRefresh = false\n ): Promise<string | null> {\n _assert(\n !this.accessToken || this.refreshToken,\n auth,\n AuthErrorCode.TOKEN_EXPIRED\n );\n\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken!);\n return this.accessToken;\n }\n\n return null;\n }\n\n clearRefreshToken(): void {\n this.refreshToken = null;\n }\n\n private async refresh(auth: AuthInternal, oldToken: string): Promise<void> {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(\n auth,\n oldToken\n );\n this.updateTokensAndExpiration(\n accessToken,\n refreshToken,\n Number(expiresIn)\n );\n }\n\n private updateTokensAndExpiration(\n accessToken: string,\n refreshToken: string,\n expiresInSec: number\n ): void {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n\n static fromJSON(appName: string, object: PersistedBlob): StsTokenManager {\n const { refreshToken, accessToken, expirationTime } = object;\n\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(\n typeof expirationTime === 'number',\n AuthErrorCode.INTERNAL_ERROR,\n {\n appName\n }\n );\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n\n toJSON(): object {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n\n _assign(stsTokenManager: StsTokenManager): void {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n\n _clone(): StsTokenManager {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n\n _performRefresh(): never {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable camelcase */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n _getFinalTarget,\n _performFetchWithErrorHandling,\n _performApiRequest,\n _addTidIfNecessary,\n HttpMethod,\n HttpHeader,\n Endpoint\n} from '../index';\nimport { FetchProvider } from '../../core/util/fetch_provider';\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\n\nexport const enum TokenType {\n REFRESH_TOKEN = 'REFRESH_TOKEN',\n ACCESS_TOKEN = 'ACCESS_TOKEN'\n}\n\n/** The server responses with snake_case; we convert to camelCase */\ninterface RequestStsTokenServerResponse {\n access_token: string;\n expires_in: string;\n refresh_token: string;\n}\n\nexport interface RequestStsTokenResponse {\n accessToken: string;\n expiresIn: string;\n refreshToken: string;\n}\n\nexport interface RevokeTokenRequest {\n providerId: string;\n tokenType: TokenType;\n token: string;\n idToken: string;\n tenantId?: string;\n}\n\nexport interface RevokeTokenResponse {}\n\nexport async function requestStsToken(\n auth: Auth,\n refreshToken: string\n): Promise<RequestStsTokenResponse> {\n const response =\n await _performFetchWithErrorHandling<RequestStsTokenServerResponse>(\n auth,\n {},\n async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = _getFinalTarget(\n auth,\n tokenApiHost,\n Endpoint.TOKEN,\n `key=${apiKey}`\n );\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/x-www-form-urlencoded';\n\n return FetchProvider.fetch()(url, {\n method: HttpMethod.POST,\n headers,\n body\n });\n }\n );\n\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\n\nexport async function revokeToken(\n auth: Auth,\n request: RevokeTokenRequest\n): Promise<RevokeTokenResponse> {\n return _performApiRequest<RevokeTokenRequest, RevokeTokenResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.REVOKE_TOKEN,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult } from '../../model/public_types';\nimport { NextFn } from '@firebase/util';\n\nimport {\n APIUserInfo,\n deleteAccount\n} from '../../api/account_management/account';\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport {\n MutableUserInfo,\n UserInternal,\n UserParameters\n} from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert } from '../util/assert';\nimport { getIdTokenResult } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { ProactiveRefresh } from './proactive_refresh';\nimport { _reloadWithoutSaving, reload } from './reload';\nimport { StsTokenManager } from './token_manager';\nimport { UserMetadata } from './user_metadata';\nimport { ProviderId } from '../../model/enums';\n\nfunction assertStringOrUndefined(\n assertion: unknown,\n appName: string\n): asserts assertion is string | undefined {\n _assert(\n typeof assertion === 'string' || typeof assertion === 'undefined',\n AuthErrorCode.INTERNAL_ERROR,\n { appName }\n );\n}\n\nexport class UserImpl implements UserInternal {\n // For the user object, provider is always Firebase.\n readonly providerId = ProviderId.FIREBASE;\n stsTokenManager: StsTokenManager;\n // Last known accessToken so we know when it changes\n private accessToken: string | null;\n\n uid: string;\n auth: AuthInternal;\n emailVerified: boolean;\n isAnonymous: boolean;\n tenantId: string | null;\n readonly metadata: UserMetadata;\n providerData: MutableUserInfo[];\n\n // Optional fields from UserInfo\n displayName: string | null;\n email: string | null;\n phoneNumber: string | null;\n photoURL: string | null;\n\n _redirectEventId?: string;\n private readonly proactiveRefresh = new ProactiveRefresh(this);\n\n constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) {\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(\n opt.createdAt || undefined,\n opt.lastLoginAt || undefined\n );\n }\n\n async getIdToken(forceRefresh?: boolean): Promise<string> {\n const accessToken = await _logoutIfInvalidated(\n this,\n this.stsTokenManager.getToken(this.auth, forceRefresh)\n );\n _assert(accessToken, this.auth, AuthErrorCode.INTERNAL_ERROR);\n\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n\n return accessToken;\n }\n\n getIdTokenResult(forceRefresh?: boolean): Promise<IdTokenResult> {\n return getIdTokenResult(this, forceRefresh);\n }\n\n reload(): Promise<void> {\n return reload(this);\n }\n\n private reloadUserInfo: APIUserInfo | null = null;\n private reloadListener: NextFn<APIUserInfo> | null = null;\n\n _assign(user: UserInternal): void {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n\n _clone(auth: AuthInternal): UserInternal {\n const newUser = new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n newUser.metadata._copy(this.metadata);\n return newUser;\n }\n\n _onReload(callback: NextFn<APIUserInfo>): void {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n\n _notifyReloadListener(userInfo: APIUserInfo): void {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n } else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n\n _startProactiveRefresh(): void {\n this.proactiveRefresh._start();\n }\n\n _stopProactiveRefresh(): void {\n this.proactiveRefresh._stop();\n }\n\n async _updateTokensIfNecessary(\n response: IdTokenResponse | FinalizeMfaResponse,\n reload = false\n ): Promise<void> {\n let tokensRefreshed = false;\n if (\n response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken\n ) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n\n async delete(): Promise<void> {\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n\n return this.auth.signOut();\n }\n\n toJSON(): PersistedBlob {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n\n get refreshToken(): string {\n return this.stsTokenManager.refreshToken || '';\n }\n\n static _fromJSON(auth: AuthInternal, object: PersistedBlob): UserInternal {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const {\n uid,\n emailVerified,\n isAnonymous,\n providerData,\n stsTokenManager: plainObjectTokenManager\n } = object;\n\n _assert(uid && plainObjectTokenManager, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const stsTokenManager = StsTokenManager.fromJSON(\n this.name,\n plainObjectTokenManager as PersistedBlob\n );\n\n _assert(typeof uid === 'string', auth, AuthErrorCode.INTERNAL_ERROR);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(\n typeof emailVerified === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof isAnonymous === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise<UserInternal> {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * Our API has a lot of one-off constants that are used to do things.\n * Unfortunately we can't export these as classes instantiated directly since\n * the constructor may side effect and therefore can't be proven to be safely\n * culled. Instead, we export these classes themselves as a lowerCamelCase\n * constant, and instantiate them under the hood.\n */\nexport interface SingletonInstantiator<T> {\n new (): T;\n}\n\nconst instanceCache: Map<unknown, unknown> = new Map();\n\nexport function _getInstance<T>(cls: unknown): T {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls) as T | undefined;\n\n if (instance) {\n debugAssert(\n instance instanceof cls,\n 'Instance stored in cache mismatched with class'\n );\n return instance;\n }\n\n instance = new (cls as SingletonInstantiator<T>)();\n instanceCache.set(cls, instance);\n return instance;\n}\n\nexport function _clearInstanceMap(): void {\n instanceCache.clear();\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../persistence';\n\nexport class InMemoryPersistence implements PersistenceInternal {\n static type: 'NONE' = 'NONE';\n readonly type = PersistenceType.NONE;\n storage: Record<string, PersistenceValue> = {};\n\n async _isAvailable(): Promise<boolean> {\n return true;\n }\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n this.storage[key] = value;\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const value = this.storage[key];\n return value === undefined ? null : (value as T);\n }\n\n async _remove(key: string): Promise<void> {\n delete this.storage[key];\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nexport const inMemoryPersistence: Persistence = InMemoryPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { PersistedBlob, PersistenceInternal } from '../persistence';\nimport { UserImpl } from '../user/user_impl';\nimport { _getInstance } from '../util/instantiator';\nimport { inMemoryPersistence } from './in_memory';\n\nexport const enum KeyName {\n AUTH_USER = 'authUser',\n AUTH_EVENT = 'authEvent',\n REDIRECT_USER = 'redirectUser',\n PERSISTENCE_USER = 'persistence'\n}\nexport const enum Namespace {\n PERSISTENCE = 'firebase'\n}\n\nexport function _persistenceKeyName(\n key: string,\n apiKey: ApiKey,\n appName: AppName\n): string {\n return `${Namespace.PERSISTENCE}:${key}:${apiKey}:${appName}`;\n}\n\nexport class PersistenceUserManager {\n private readonly fullUserKey: string;\n private readonly fullPersistenceKey: string;\n private readonly boundEventHandler: () => void;\n\n private constructor(\n public persistence: PersistenceInternal,\n private readonly auth: AuthInternal,\n private readonly userKey: string\n ) {\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\n KeyName.PERSISTENCE_USER,\n config.apiKey,\n name\n );\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n\n setCurrentUser(user: UserInternal): Promise<void> {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n\n async getCurrentUser(): Promise<UserInternal | null> {\n const blob = await this.persistence._get<PersistedBlob>(this.fullUserKey);\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\n }\n\n removeCurrentUser(): Promise<void> {\n return this.persistence._remove(this.fullUserKey);\n }\n\n savePersistenceForRedirect(): Promise<void> {\n return this.persistence._set(\n this.fullPersistenceKey,\n this.persistence.type\n );\n }\n\n async setPersistence(newPersistence: PersistenceInternal): Promise<void> {\n if (this.persistence === newPersistence) {\n return;\n }\n\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n\n this.persistence = newPersistence;\n\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n\n delete(): void {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n\n static async create(\n auth: AuthInternal,\n persistenceHierarchy: PersistenceInternal[],\n userKey = KeyName.AUTH_USER\n ): Promise<PersistenceUserManager> {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(\n _getInstance(inMemoryPersistence),\n auth,\n userKey\n );\n }\n\n // Eliminate any persistences that are not available\n const availablePersistences = (\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n return undefined;\n })\n )\n ).filter(persistence => persistence) as PersistenceInternal[];\n\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence =\n availablePersistences[0] ||\n _getInstance<PersistenceInternal>(inMemoryPersistence);\n\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate: UserInternal | null = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get<PersistedBlob>(key);\n if (blob) {\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n } catch {}\n }\n\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(\n p => p._shouldAllowMigration\n );\n\n // If the persistence does _not_ allow migration, just finish off here\n if (\n !selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length\n ) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n } catch {}\n }\n })\n );\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIE, getUA } from '@firebase/util';\n\ninterface NavigatorStandalone extends Navigator {\n standalone?: unknown;\n}\n\ninterface Document {\n documentMode?: number;\n}\n\n/**\n * Enums for Browser name.\n */\nexport const enum 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 * Determine the browser for the purposes of reporting usage to the API\n */\nexport function _getBrowserName(userAgent: string): BrowserName | string {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return BrowserName.OPERA;\n } else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return BrowserName.IEMOBILE;\n } else if (ua.includes('msie') || ua.includes('trident/')) {\n return BrowserName.IE;\n } else if (ua.includes('edge/')) {\n return BrowserName.EDGE;\n } else if (_isFirefox(ua)) {\n return BrowserName.FIREFOX;\n } else if (ua.includes('silk/')) {\n return BrowserName.SILK;\n } else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return BrowserName.BLACKBERRY;\n } else if (_isWebOS(ua)) {\n // WebOS default browser.\n return BrowserName.WEBOS;\n } else if (_isSafari(ua)) {\n return BrowserName.SAFARI;\n } else if (\n (ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')\n ) {\n return BrowserName.CHROME;\n } else if (_isAndroid(ua)) {\n // Android stock browser.\n return BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return BrowserName.OTHER;\n}\n\nexport function _isFirefox(ua = getUA()): boolean {\n return /firefox\\//i.test(ua);\n}\n\nexport function _isSafari(userAgent = getUA()): boolean {\n const ua = userAgent.toLowerCase();\n return (\n ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android')\n );\n}\n\nexport function _isChromeIOS(ua = getUA()): boolean {\n return /crios\\//i.test(ua);\n}\n\nexport function _isIEMobile(ua = getUA()): boolean {\n return /iemobile/i.test(ua);\n}\n\nexport function _isAndroid(ua = getUA()): boolean {\n return /android/i.test(ua);\n}\n\nexport function _isBlackBerry(ua = getUA()): boolean {\n return /blackberry/i.test(ua);\n}\n\nexport function _isWebOS(ua = getUA()): boolean {\n return /webos/i.test(ua);\n}\n\nexport function _isIOS(ua = getUA()): boolean {\n return (\n /iphone|ipad|ipod/i.test(ua) ||\n (/macintosh/i.test(ua) && /mobile/i.test(ua))\n );\n}\n\nexport function _isIOS7Or8(ua = getUA()): boolean {\n return (\n /(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua)\n );\n}\n\nexport function _isIOSStandalone(ua = getUA()): boolean {\n return _isIOS(ua) && !!(window.navigator as NavigatorStandalone)?.standalone;\n}\n\nexport function _isIE10(): boolean {\n return isIE() && (document as Document).documentMode === 10;\n}\n\nexport function _isMobileBrowser(ua: string = getUA()): boolean {\n // TODO: implement getBrowserName equivalent for OS.\n return (\n _isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua)\n );\n}\n\nexport function _isIframe(): boolean {\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(window && window !== window.top);\n } catch (e) {\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { _getBrowserName } from './browser';\nimport { getUA } from '@firebase/util';\n\nexport const enum ClientImplementation {\n CORE = 'JsCore'\n}\n\n/**\n * @internal\n */\nexport const enum ClientPlatform {\n BROWSER = 'Browser',\n NODE = 'Node',\n REACT_NATIVE = 'ReactNative',\n CORDOVA = 'Cordova',\n WORKER = 'Worker',\n WEB_EXTENSION = 'WebExtension'\n}\n\n/*\n * Determine the SDK version string\n */\nexport function _getClientVersion(\n clientPlatform: ClientPlatform,\n frameworks: readonly string[] = []\n): string {\n let reportedPlatform: string;\n switch (clientPlatform) {\n case ClientPlatform.BROWSER:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case ClientPlatform.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 reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${ClientImplementation.CORE}/${SDK_VERSION}/${reportedFrameworks}`;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport { Unsubscribe, User } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\n\ninterface MiddlewareEntry {\n (user: User | null): Promise<void>;\n onAbort?: () => void;\n}\n\nexport class AuthMiddlewareQueue {\n private readonly queue: MiddlewareEntry[] = [];\n\n constructor(private readonly auth: AuthInternal) {}\n\n pushCallback(\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n ): Unsubscribe {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback: MiddlewareEntry = (\n user: User | null\n ): Promise<void> =>\n new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n } catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n\n async runMiddleware(nextUser: User | null): Promise<void> {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n\n const onAbortStack: Array<() => void> = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n } catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n } catch (_) {\n /* swallow error */\n }\n }\n\n throw this.auth._errorFactory.create(AuthErrorCode.LOGIN_BLOCKED, {\n originalMessage: (e as Error)?.message\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetPasswordPolicyResponse } from '../../api/password_policy/get_password_policy';\nimport {\n PasswordPolicyCustomStrengthOptions,\n PasswordPolicyInternal,\n PasswordValidationStatusInternal\n} from '../../model/password_policy';\nimport { PasswordValidationStatus } from '../../model/public_types';\n\n// Minimum min password length enforced by the backend, even if no minimum length is set.\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\n\n/**\n * Stores password policy requirements and provides password validation against the policy.\n *\n * @internal\n */\nexport class PasswordPolicyImpl implements PasswordPolicyInternal {\n readonly customStrengthOptions: PasswordPolicyCustomStrengthOptions;\n readonly allowedNonAlphanumericCharacters: string;\n readonly enforcementState: string;\n readonly forceUpgradeOnSignin: boolean;\n readonly schemaVersion: number;\n\n constructor(response: GetPasswordPolicyResponse) {\n // Only include custom strength options defined in the response.\n const responseOptions = response.customStrengthOptions;\n this.customStrengthOptions = {};\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\n this.customStrengthOptions.minPasswordLength =\n responseOptions.minPasswordLength ?? MINIMUM_MIN_PASSWORD_LENGTH;\n if (responseOptions.maxPasswordLength) {\n this.customStrengthOptions.maxPasswordLength =\n responseOptions.maxPasswordLength;\n }\n if (responseOptions.containsLowercaseCharacter !== undefined) {\n this.customStrengthOptions.containsLowercaseLetter =\n responseOptions.containsLowercaseCharacter;\n }\n if (responseOptions.containsUppercaseCharacter !== undefined) {\n this.customStrengthOptions.containsUppercaseLetter =\n responseOptions.containsUppercaseCharacter;\n }\n if (responseOptions.containsNumericCharacter !== undefined) {\n this.customStrengthOptions.containsNumericCharacter =\n responseOptions.containsNumericCharacter;\n }\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\n this.customStrengthOptions.containsNonAlphanumericCharacter =\n responseOptions.containsNonAlphanumericCharacter;\n }\n\n this.enforcementState = response.enforcementState;\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\n this.enforcementState = 'OFF';\n }\n\n // Use an empty string if no non-alphanumeric characters are specified in the response.\n this.allowedNonAlphanumericCharacters =\n response.allowedNonAlphanumericCharacters?.join('') ?? '';\n\n this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ?? false;\n this.schemaVersion = response.schemaVersion;\n }\n\n validatePassword(password: string): PasswordValidationStatus {\n const status: PasswordValidationStatusInternal = {\n isValid: true,\n passwordPolicy: this\n };\n\n // Check the password length and character options.\n this.validatePasswordLengthOptions(password, status);\n this.validatePasswordCharacterOptions(password, status);\n\n // Combine the status into single isValid property.\n status.isValid &&= status.meetsMinPasswordLength ?? true;\n status.isValid &&= status.meetsMaxPasswordLength ?? true;\n status.isValid &&= status.containsLowercaseLetter ?? true;\n status.isValid &&= status.containsUppercaseLetter ?? true;\n status.isValid &&= status.containsNumericCharacter ?? true;\n status.isValid &&= status.containsNonAlphanumericCharacter ?? true;\n\n return status;\n }\n\n /**\n * Validates that the password meets the length options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordLengthOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\n if (minPasswordLength) {\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\n }\n if (maxPasswordLength) {\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\n }\n }\n\n /**\n * Validates that the password meets the character options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordCharacterOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n // Assign statuses for requirements even if the password is an empty string.\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ false,\n /* containsUppercaseCharacter= */ false,\n /* containsNumericCharacter= */ false,\n /* containsNonAlphanumericCharacter= */ false\n );\n\n let passwordChar;\n for (let i = 0; i < password.length; i++) {\n passwordChar = password.charAt(i);\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\n passwordChar <= 'z',\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\n passwordChar <= 'Z',\n /* containsNumericCharacter= */ passwordChar >= '0' &&\n passwordChar <= '9',\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(\n passwordChar\n )\n );\n }\n }\n\n /**\n * Updates the running validation status with the statuses for the character options.\n * Expected to be called each time a character is processed to update each option status\n * based on the current character.\n *\n * @param status Validation status.\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\n * @param containsNumericCharacter Whether the character is a numeric character.\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\n */\n private updatePasswordCharacterOptionsStatuses(\n status: PasswordValidationStatusInternal,\n containsLowercaseCharacter: boolean,\n containsUppercaseCharacter: boolean,\n containsNumericCharacter: boolean,\n containsNonAlphanumericCharacter: boolean\n ): void {\n if (this.customStrengthOptions.containsLowercaseLetter) {\n status.containsLowercaseLetter ||= containsLowercaseCharacter;\n }\n if (this.customStrengthOptions.containsUppercaseLetter) {\n status.containsUppercaseLetter ||= containsUppercaseCharacter;\n }\n if (this.customStrengthOptions.containsNumericCharacter) {\n status.containsNumericCharacter ||= containsNumericCharacter;\n }\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\n status.containsNonAlphanumericCharacter ||=\n containsNonAlphanumericCharacter;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _FirebaseService, FirebaseApp } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport {\n Auth,\n AuthErrorMap,\n AuthSettings,\n EmulatorConfig,\n NextOrObserver,\n Persistence,\n PopupRedirectResolver,\n User,\n UserCredential,\n CompleteFn,\n ErrorFn,\n NextFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../../model/public_types';\nimport {\n createSubscribe,\n ErrorFactory,\n FirebaseError,\n getModularInstance,\n Observer,\n Subscribe\n} from '@firebase/util';\n\nimport { AuthInternal, ConfigInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport {\n AuthErrorCode,\n AuthErrorParams,\n ErrorMapRetriever,\n _DEFAULT_AUTH_ERROR_FACTORY\n} from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport {\n KeyName,\n PersistenceUserManager\n} from '../persistence/persistence_user_manager';\nimport { _reloadWithoutSaving } from '../user/reload';\nimport { _assert } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { _getUserLanguage } from '../util/navigator';\nimport { _getClientVersion } from '../util/version';\nimport { HttpHeader } from '../../api';\nimport {\n RevokeTokenRequest,\n TokenType,\n revokeToken\n} from '../../api/authentication/token';\nimport { AuthMiddlewareQueue } from './middleware';\nimport { RecaptchaConfig } from '../../platform_browser/recaptcha/recaptcha';\nimport { _logWarn } from '../util/log';\nimport { _getPasswordPolicy } from '../../api/password_policy/get_password_policy';\nimport { PasswordPolicyInternal } from '../../model/password_policy';\nimport { PasswordPolicyImpl } from './password_policy_impl';\n\ninterface AsyncAction {\n (): Promise<void>;\n}\n\nexport const enum DefaultConfig {\n TOKEN_API_HOST = 'securetoken.googleapis.com',\n API_HOST = 'identitytoolkit.googleapis.com',\n API_SCHEME = 'https'\n}\n\nexport class AuthImpl implements AuthInternal, _FirebaseService {\n currentUser: User | null = null;\n emulatorConfig: EmulatorConfig | null = null;\n private operations = Promise.resolve();\n private persistenceManager?: PersistenceUserManager;\n private redirectPersistenceManager?: PersistenceUserManager;\n private authStateSubscription = new Subscription<User>(this);\n private idTokenSubscription = new Subscription<User>(this);\n private readonly beforeStateQueue = new AuthMiddlewareQueue(this);\n private redirectUser: UserInternal | null = null;\n private isProactiveRefreshEnabled = false;\n private readonly EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION: number = 1;\n\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n _canInitEmulator = true;\n _isInitialized = false;\n _deleted = false;\n _initializationPromise: Promise<void> | null = null;\n _popupRedirectResolver: PopupRedirectResolverInternal | null = null;\n _errorFactory: ErrorFactory<AuthErrorCode, AuthErrorParams> =\n _DEFAULT_AUTH_ERROR_FACTORY;\n _agentRecaptchaConfig: RecaptchaConfig | null = null;\n _tenantRecaptchaConfigs: Record<string, RecaptchaConfig> = {};\n _projectPasswordPolicy: PasswordPolicyInternal | null = null;\n _tenantPasswordPolicies: Record<string, PasswordPolicyInternal> = {};\n readonly name: string;\n\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n private lastNotifiedUid: string | null | undefined = undefined;\n\n languageCode: string | null = null;\n tenantId: string | null = null;\n settings: AuthSettings = { appVerificationDisabledForTesting: false };\n\n constructor(\n public readonly app: FirebaseApp,\n private readonly heartbeatServiceProvider: Provider<'heartbeat'>,\n private readonly appCheckServiceProvider: Provider<AppCheckInternalComponentName>,\n public readonly config: ConfigInternal\n ) {\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n }\n\n _initializeWithPersistence(\n persistenceHierarchy: PersistenceInternal[],\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n\n this.persistenceManager = await PersistenceUserManager.create(\n this,\n persistenceHierarchy\n );\n\n if (this._deleted) {\n return;\n }\n\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n } catch (e) {\n /* Ignore the error */\n }\n }\n\n await this.initializeCurrentUser(popupRedirectResolver);\n this.lastNotifiedUid = this.currentUser?.uid || null;\n\n if (this._deleted) {\n return;\n }\n\n this._isInitialized = true;\n });\n\n return this._initializationPromise;\n }\n\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent(): Promise<void> {\n if (this._deleted) {\n return;\n }\n\n const user = await this.assertedPersistence.getCurrentUser();\n\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n\n private async initializeCurrentUser(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser =\n (await this.assertedPersistence.getCurrentUser()) as UserInternal | null;\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if (\n (!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user\n ) {\n futureCurrentUser = result.user as UserInternal;\n needsTocheckMiddleware = true;\n }\n }\n\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n } catch (e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver!._overrideRedirectResult(this, () =>\n Promise.reject(e)\n );\n }\n }\n\n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n _assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);\n await this.getOrInitRedirectPersistenceManager();\n\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (\n this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId\n ) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n\n private async tryRedirectSignIn(\n redirectResolver: PopupRedirectResolver\n ): Promise<UserCredential | null> {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [<other queue tasks>] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n\n let result: UserCredential | null = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver!._completeRedirectFn(\n this,\n redirectResolver,\n true\n );\n } catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n\n return result;\n }\n\n private async reloadAndSetCurrentUserOrClear(\n user: UserInternal\n ): Promise<void> {\n try {\n await _reloadWithoutSaving(user);\n } catch (e) {\n if (\n (e as FirebaseError)?.code !==\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n\n return this.directlySetCurrentUser(user);\n }\n\n useDeviceLanguage(): void {\n this.languageCode = _getUserLanguage();\n }\n\n async _delete(): Promise<void> {\n this._deleted = true;\n }\n\n async updateCurrentUser(userExtern: User | null): Promise<void> {\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? (getModularInstance(userExtern) as UserInternal)\n : null;\n if (user) {\n _assert(\n user.auth.config.apiKey === this.config.apiKey,\n this,\n AuthErrorCode.INVALID_AUTH\n );\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n\n async _updateCurrentUser(\n user: User | null,\n skipBeforeStateCallbacks: boolean = false\n ): Promise<void> {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(\n this.tenantId === user.tenantId,\n this,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n }\n\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n\n return this.queue(async () => {\n await this.directlySetCurrentUser(user as UserInternal | null);\n this.notifyAuthListeners();\n });\n }\n\n async signOut(): Promise<void> {\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n\n setPersistence(persistence: Persistence): Promise<void> {\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n\n _getRecaptchaConfig(): RecaptchaConfig | null {\n if (this.tenantId == null) {\n return this._agentRecaptchaConfig;\n } else {\n return this._tenantRecaptchaConfigs[this.tenantId];\n }\n }\n\n async validatePassword(password: string): Promise<PasswordValidationStatus> {\n if (!this._getPasswordPolicyInternal()) {\n await this._updatePasswordPolicy();\n }\n\n // Password policy will be defined after fetching.\n const passwordPolicy: PasswordPolicyInternal =\n this._getPasswordPolicyInternal()!;\n\n // Check that the policy schema version is supported by the SDK.\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\n if (\n passwordPolicy.schemaVersion !==\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION\n ) {\n return Promise.reject(\n this._errorFactory.create(\n AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION,\n {}\n )\n );\n }\n\n return passwordPolicy.validatePassword(password);\n }\n\n _getPasswordPolicyInternal(): PasswordPolicyInternal | null {\n if (this.tenantId === null) {\n return this._projectPasswordPolicy;\n } else {\n return this._tenantPasswordPolicies[this.tenantId];\n }\n }\n\n async _updatePasswordPolicy(): Promise<void> {\n const response = await _getPasswordPolicy(this);\n\n const passwordPolicy: PasswordPolicyInternal = new PasswordPolicyImpl(\n response\n );\n\n if (this.tenantId === null) {\n this._projectPasswordPolicy = passwordPolicy;\n } else {\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\n }\n }\n\n _getPersistence(): string {\n return this.assertedPersistence.persistence.type;\n }\n\n _updateErrorMap(errorMap: AuthErrorMap): void {\n this._errorFactory = new ErrorFactory<AuthErrorCode, AuthErrorParams>(\n 'auth',\n 'Firebase',\n (errorMap as ErrorMapRetriever)()\n );\n }\n\n onAuthStateChanged(\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.authStateSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n beforeAuthStateChanged(\n callback: (user: User | null) => void | Promise<void>,\n onAbort?: () => void\n ): Unsubscribe {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n\n onIdTokenChanged(\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.idTokenSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n authStateReady(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (this.currentUser) {\n resolve();\n } else {\n const unsubscribe = this.onAuthStateChanged(() => {\n unsubscribe();\n resolve();\n }, reject);\n }\n });\n }\n\n /**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n */\n async revokeAccessToken(token: string): Promise<void> {\n if (this.currentUser) {\n const idToken = await this.currentUser.getIdToken();\n // Generalize this to accept other providers once supported.\n const request: RevokeTokenRequest = {\n providerId: 'apple.com',\n tokenType: TokenType.ACCESS_TOKEN,\n token,\n idToken\n };\n if (this.tenantId != null) {\n request.tenantId = this.tenantId;\n }\n await revokeToken(this, request);\n }\n }\n\n toJSON(): object {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n\n async _setRedirectUser(\n user: UserInternal | null,\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<void> {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(\n popupRedirectResolver\n );\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n\n private async getOrInitRedirectPersistenceManager(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise<PersistenceUserManager> {\n if (!this.redirectPersistenceManager) {\n const resolver: PopupRedirectResolverInternal | null =\n (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);\n this.redirectPersistenceManager = await PersistenceUserManager.create(\n this,\n [_getInstance(resolver._redirectPersistence)],\n KeyName.REDIRECT_USER\n );\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n\n return this.redirectPersistenceManager;\n }\n\n async _redirectUserForId(id: string): Promise<UserInternal | null> {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => {});\n }\n\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n\n return null;\n }\n\n async _persistUserIfCurrent(user: UserInternal): Promise<void> {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user: UserInternal): void {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n\n _key(): string {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n\n _startProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n\n _stopProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n\n /** Returns the current user cast as the internal type */\n get _currentUser(): UserInternal {\n return this.currentUser as UserInternal;\n }\n\n private notifyAuthListeners(): void {\n if (!this._isInitialized) {\n return;\n }\n\n this.idTokenSubscription.next(this.currentUser);\n\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n\n private registerStateListener(\n subscription: Subscription<User>,\n nextOrObserver: NextOrObserver<User>,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n if (this._deleted) {\n return () => {};\n }\n\n const cb =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n\n let isUnsubscribed = false;\n\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, AuthErrorCode.INTERNAL_ERROR);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise.then(() => {\n if (isUnsubscribed) {\n return;\n }\n cb(this.currentUser);\n });\n\n if (typeof nextOrObserver === 'function') {\n const unsubscribe = subscription.addObserver(\n nextOrObserver,\n error,\n completed\n );\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n } else {\n const unsubscribe = subscription.addObserver(nextOrObserver);\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n }\n }\n\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n private async directlySetCurrentUser(\n user: UserInternal | null\n ): Promise<void> {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n }\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n\n this.currentUser = user;\n\n if (user) {\n await this.assertedPersistence.setCurrentUser(user);\n } else {\n await this.assertedPersistence.removeCurrentUser();\n }\n }\n\n private queue(action: AsyncAction): Promise<void> {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n\n private get assertedPersistence(): PersistenceUserManager {\n _assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);\n return this.persistenceManager;\n }\n\n private frameworks: string[] = [];\n private clientVersion: string;\n _logFramework(framework: string): void {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(\n this.config.clientPlatform,\n this._getFrameworks()\n );\n }\n _getFrameworks(): readonly string[] {\n return this.frameworks;\n }\n async _getAdditionalHeaders(): Promise<Record<string, string>> {\n // Additional headers on every request\n const headers: Record<string, string> = {\n [HttpHeader.X_CLIENT_VERSION]: this.clientVersion\n };\n\n if (this.app.options.appId) {\n headers[HttpHeader.X_FIREBASE_GMPID] = this.app.options.appId;\n }\n\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider\n .getImmediate({\n optional: true\n })\n ?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[HttpHeader.X_FIREBASE_CLIENT] = heartbeatsHeader;\n }\n\n // If the App Check service exists, add the App Check token in the headers\n const appCheckToken = await this._getAppCheckToken();\n if (appCheckToken) {\n headers[HttpHeader.X_FIREBASE_APP_CHECK] = appCheckToken;\n }\n\n return headers;\n }\n\n async _getAppCheckToken(): Promise<string | undefined> {\n const appCheckTokenResult = await this.appCheckServiceProvider\n .getImmediate({ optional: true })\n ?.getToken();\n if (appCheckTokenResult?.error) {\n // Context: appCheck.getToken() will never throw even if an error happened.\n // In the error case, a dummy token will be returned along with an error field describing\n // the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n _logWarn(\n `Error while retrieving App Check token: ${appCheckTokenResult.error}`\n );\n }\n return appCheckTokenResult?.token;\n }\n}\n\n/**\n * Method to be used to cast down to our private implmentation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nexport function _castAuth(auth: Auth): AuthInternal {\n return getModularInstance(auth) as AuthInternal;\n}\n\n/** Helper class to wrap subscriber logic */\nclass Subscription<T> {\n private observer: Observer<T | null> | null = null;\n readonly addObserver: Subscribe<T | null> = createSubscribe(\n observer => (this.observer = observer)\n );\n\n constructor(readonly auth: AuthInternal) {}\n\n get next(): NextFn<T | null> {\n _assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.observer.next.bind(this.observer);\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\n/**\n * Request object for fetching the password policy.\n */\nexport interface GetPasswordPolicyRequest {\n tenantId?: string;\n}\n\n/**\n * Response object for fetching the password policy.\n */\nexport interface GetPasswordPolicyResponse {\n customStrengthOptions: {\n minPasswordLength?: number;\n maxPasswordLength?: number;\n containsLowercaseCharacter?: boolean;\n containsUppercaseCharacter?: boolean;\n containsNumericCharacter?: boolean;\n containsNonAlphanumericCharacter?: boolean;\n };\n allowedNonAlphanumericCharacters?: string[];\n enforcementState: string;\n forceUpgradeOnSignin?: boolean;\n schemaVersion: number;\n}\n\n/**\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\n *\n * @param auth Auth object.\n * @param request Password policy request.\n * @returns Password policy response.\n */\nexport async function _getPasswordPolicy(\n auth: Auth,\n request: GetPasswordPolicyRequest = {}\n): Promise<GetPasswordPolicyResponse> {\n return _performApiRequest<\n GetPasswordPolicyRequest,\n GetPasswordPolicyResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PASSWORD_POLICY,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ninterface ExternalJSProvider {\n loadJS(url: string): Promise<Event>;\n recaptchaV2Script: string;\n recaptchaEnterpriseScript: string;\n gapiScript: string;\n}\n\nlet externalJSProvider: ExternalJSProvider = {\n async loadJS() {\n throw new Error('Unable to load external scripts');\n },\n\n recaptchaV2Script: '',\n recaptchaEnterpriseScript: '',\n gapiScript: ''\n};\n\nexport function _setExternalJSProvider(p: ExternalJSProvider): void {\n externalJSProvider = p;\n}\n\nexport function _loadJS(url: string): Promise<Event> {\n return externalJSProvider.loadJS(url);\n}\n\nexport function _recaptchaV2ScriptUrl(): string {\n return externalJSProvider.recaptchaV2Script;\n}\n\nexport function _recaptchaEnterpriseScriptUrl(): string {\n return externalJSProvider.recaptchaEnterpriseScript;\n}\n\nexport function _gapiScriptUrl(): string {\n return externalJSProvider.gapiScript;\n}\n\nexport function _generateCallbackName(prefix: string): string {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n","/* eslint-disable @typescript-eslint/no-require-imports */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isEnterprise, RecaptchaConfig } from './recaptcha';\nimport { getRecaptchaConfig } from '../../api/authentication/recaptcha';\nimport {\n RecaptchaClientType,\n RecaptchaVersion,\n RecaptchaActionName,\n RecaptchaProvider\n} from '../../api';\n\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport * as jsHelpers from '../load_js';\nimport { AuthErrorCode } from '../../core/errors';\n\nexport const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\nexport const FAKE_TOKEN = 'NO_RECAPTCHA';\n\nexport class RecaptchaEnterpriseVerifier {\n /**\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\n */\n readonly type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\n\n private readonly auth: AuthInternal;\n\n /**\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n */\n constructor(authExtern: Auth) {\n this.auth = _castAuth(authExtern);\n }\n\n /**\n * Executes the verification process.\n *\n * @returns A Promise for a token that can be used to assert the validity of a request.\n */\n async verify(\n action: string = 'verify',\n forceRefresh = false\n ): Promise<string> {\n async function retrieveSiteKey(auth: AuthInternal): Promise<string> {\n if (!forceRefresh) {\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\n return auth._agentRecaptchaConfig.siteKey;\n }\n if (\n auth.tenantId != null &&\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined\n ) {\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\n }\n }\n\n return new Promise<string>(async (resolve, reject) => {\n getRecaptchaConfig(auth, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n })\n .then(response => {\n if (response.recaptchaKey === undefined) {\n reject(new Error('recaptcha Enterprise site key undefined'));\n } else {\n const config = new RecaptchaConfig(response);\n if (auth.tenantId == null) {\n auth._agentRecaptchaConfig = config;\n } else {\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\n }\n return resolve(config.siteKey);\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n\n function retrieveRecaptchaToken(\n siteKey: string,\n resolve: (value: string | PromiseLike<string>) => void,\n reject: (reason?: unknown) => void\n ): void {\n const grecaptcha = window.grecaptcha;\n if (isEnterprise(grecaptcha)) {\n grecaptcha.enterprise.ready(() => {\n grecaptcha.enterprise\n .execute(siteKey, { action })\n .then(token => {\n resolve(token);\n })\n .catch(() => {\n resolve(FAKE_TOKEN);\n });\n });\n } else {\n reject(Error('No reCAPTCHA enterprise script loaded.'));\n }\n }\n\n return new Promise<string>((resolve, reject) => {\n retrieveSiteKey(this.auth)\n .then(siteKey => {\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n } else {\n if (typeof window === 'undefined') {\n reject(\n new Error('RecaptchaVerifier is only supported in browser')\n );\n return;\n }\n let url = jsHelpers._recaptchaEnterpriseScriptUrl();\n if (url.length !== 0) {\n url += siteKey;\n }\n jsHelpers\n ._loadJS(url)\n .then(() => {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n })\n .catch(error => {\n reject(error);\n });\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n}\n\nexport async function injectRecaptchaFields<T>(\n auth: AuthInternal,\n request: T,\n action: RecaptchaActionName,\n captchaResp = false\n): Promise<T> {\n const verifier = new RecaptchaEnterpriseVerifier(auth);\n let captchaResponse;\n try {\n captchaResponse = await verifier.verify(action);\n } catch (error) {\n captchaResponse = await verifier.verify(action, true);\n }\n const newRequest = { ...request };\n if (!captchaResp) {\n Object.assign(newRequest, { captchaResponse });\n } else {\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\n }\n Object.assign(newRequest, { 'clientType': RecaptchaClientType.WEB });\n Object.assign(newRequest, {\n 'recaptchaVersion': RecaptchaVersion.ENTERPRISE\n });\n return newRequest;\n}\n\ntype ActionMethod<TRequest, TResponse> = (\n auth: Auth,\n request: TRequest\n) => Promise<TResponse>;\n\nexport async function handleRecaptchaFlow<TRequest, TResponse>(\n authInstance: AuthInternal,\n request: TRequest,\n actionName: RecaptchaActionName,\n actionMethod: ActionMethod<TRequest, TResponse>\n): Promise<TResponse> {\n if (\n authInstance\n ._getRecaptchaConfig()\n ?.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)\n ) {\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return actionMethod(authInstance, request).catch(async error => {\n if (error.code === `auth/${AuthErrorCode.MISSING_RECAPTCHA_TOKEN}`) {\n console.log(\n `${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`\n );\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return Promise.reject(error);\n }\n });\n }\n}\n\nexport async function _initializeRecaptchaConfig(auth: Auth): Promise<void> {\n const authInternal = _castAuth(auth);\n\n const response = await getRecaptchaConfig(authInternal, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n });\n\n const config = new RecaptchaConfig(response);\n if (authInternal.tenantId == null) {\n authInternal._agentRecaptchaConfig = config;\n } else {\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\n }\n\n if (config.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)) {\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\n void verifier.verify();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _performApiRequest,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\ninterface GetRecaptchaParamResponse {\n recaptchaSiteKey?: string;\n}\n\nexport async function getRecaptchaParams(auth: Auth): Promise<string> {\n return (\n (\n await _performApiRequest<void, GetRecaptchaParamResponse>(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_PARAM\n )\n ).recaptchaSiteKey || ''\n );\n}\n\n// The following functions are for reCAPTCHA enterprise integration.\ninterface GetRecaptchaConfigRequest {\n tenantId?: string;\n clientType?: RecaptchaClientType;\n version?: RecaptchaVersion;\n}\n\nexport interface RecaptchaEnforcementProviderState {\n provider: string;\n enforcementState: string;\n}\n\nexport interface GetRecaptchaConfigResponse {\n recaptchaKey: string;\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[];\n}\n\nexport async function getRecaptchaConfig(\n auth: Auth,\n request: GetRecaptchaConfigRequest\n): Promise<GetRecaptchaConfigResponse> {\n return _performApiRequest<\n GetRecaptchaConfigRequest,\n GetRecaptchaConfigResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_CONFIG,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Auth } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _castAuth } from './auth_impl';\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nexport function connectAuthEmulator(\n auth: Auth,\n url: string,\n options?: { disableWarnings: boolean }\n): void {\n const authInternal = _castAuth(auth);\n _assert(\n authInternal._canInitEmulator,\n authInternal,\n AuthErrorCode.EMULATOR_CONFIG_FAILED\n );\n\n _assert(\n /^https?:\\/\\//.test(url),\n authInternal,\n AuthErrorCode.INVALID_EMULATOR_SCHEME\n );\n\n const disableWarnings = !!options?.disableWarnings;\n\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\n authInternal.settings.appVerificationDisabledForTesting = true;\n authInternal.emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n\n if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\n\nfunction extractProtocol(url: string): string {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\n\nfunction extractHostAndPort(url: string): {\n host: string;\n port: number | null;\n} {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n } else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\n\nfunction parsePort(portStr: string): number | null {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\n\nfunction emitEmulatorWarning(): void {\n function attachBanner(): void {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info(\n 'WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.'\n );\n }\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n } else {\n attachBanner();\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { debugFail } from '../util/assert';\n\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class AuthCredential {\n /** @internal */\n protected constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n readonly providerId: string,\n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n readonly signInMethod: string\n ) {}\n\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON(): object {\n return debugFail('not implemented');\n }\n\n /** @internal */\n _getIdTokenResponse(_auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(\n _auth: AuthInternal,\n _idToken: string\n ): Promise<IdTokenResponse> {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth: AuthInternal): Promise<IdTokenResponse> {\n return debugFail('not implemented');\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from './mfa';\nimport { SignUpRequest, SignUpResponse } from '../authentication/sign_up';\n\nexport interface ResetPasswordRequest {\n oobCode: string;\n newPassword?: string;\n tenantId?: string;\n}\n\nexport interface ResetPasswordResponse {\n email: string;\n newEmail?: string;\n requestType?: ActionCodeOperation;\n mfaInfo?: MfaEnrollment;\n}\n\nexport async function resetPassword(\n auth: Auth,\n request: ResetPasswordRequest\n): Promise<ResetPasswordResponse> {\n return _performApiRequest<ResetPasswordRequest, ResetPasswordResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.RESET_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface UpdateEmailPasswordRequest {\n idToken: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n}\n\nexport interface UpdateEmailPasswordResponse extends IdTokenResponse {}\n\nexport async function updateEmailPassword(\n auth: Auth,\n request: UpdateEmailPasswordRequest\n): Promise<UpdateEmailPasswordResponse> {\n return _performApiRequest<\n UpdateEmailPasswordRequest,\n UpdateEmailPasswordResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\n// format as updateEmailPassword.\nexport async function linkEmailPassword(\n auth: Auth,\n request: SignUpRequest\n): Promise<SignUpResponse> {\n return _performApiRequest<SignUpRequest, SignUpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n request\n );\n}\n\nexport interface ApplyActionCodeRequest {\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface ApplyActionCodeResponse {}\n\nexport async function applyActionCode(\n auth: Auth,\n request: ApplyActionCodeRequest\n): Promise<ApplyActionCodeResponse> {\n return _performApiRequest<ApplyActionCodeRequest, ApplyActionCodeResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\n\nexport interface SignInWithPasswordRequest {\n returnSecureToken?: boolean;\n email: string;\n password: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignInWithPasswordResponse extends IdTokenResponse {\n email: string;\n displayName: string;\n}\n\nexport async function signInWithPassword(\n auth: Auth,\n request: SignInWithPasswordRequest\n): Promise<SignInWithPasswordResponse> {\n return _performSignInRequest<\n SignInWithPasswordRequest,\n SignInWithPasswordResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface GetOobCodeRequest {\n email?: string; // Everything except VERIFY_AND_CHANGE_EMAIL\n continueUrl?: string;\n iOSBundleId?: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n androidInstallApp?: boolean;\n androidMinimumVersionCode?: string;\n canHandleCodeInApp?: boolean;\n dynamicLinkDomain?: string;\n tenantId?: string;\n targetProjectid?: string;\n}\n\nexport interface VerifyEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_EMAIL;\n idToken: IdToken;\n}\n\nexport interface PasswordResetRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.PASSWORD_RESET;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface EmailSignInRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.EMAIL_SIGNIN;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface VerifyAndChangeEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n idToken: IdToken;\n newEmail: string;\n}\n\ninterface GetOobCodeResponse {\n email: string;\n}\n\nexport interface VerifyEmailResponse extends GetOobCodeResponse {}\nexport interface PasswordResetResponse extends GetOobCodeResponse {}\nexport interface EmailSignInResponse extends GetOobCodeResponse {}\nexport interface VerifyAndChangeEmailResponse extends GetOobCodeRequest {}\n\nasync function sendOobCode(\n auth: Auth,\n request: GetOobCodeRequest\n): Promise<GetOobCodeResponse> {\n return _performApiRequest<GetOobCodeRequest, GetOobCodeResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_OOB_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function sendEmailVerification(\n auth: Auth,\n request: VerifyEmailRequest\n): Promise<VerifyEmailResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function sendPasswordResetEmail(\n auth: Auth,\n request: PasswordResetRequest\n): Promise<PasswordResetResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n request: EmailSignInRequest\n): Promise<EmailSignInResponse> {\n return sendOobCode(auth, request);\n}\n\nexport async function verifyAndChangeEmail(\n auth: Auth,\n request: VerifyAndChangeEmailRequest\n): Promise<VerifyAndChangeEmailResponse> {\n return sendOobCode(auth, request);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { linkEmailPassword } from '../../api/account_management/email_and_password';\nimport {\n signInWithPassword,\n SignInWithPasswordRequest\n} from '../../api/authentication/email_and_password';\nimport {\n signInWithEmailLink,\n signInWithEmailLinkForLinking\n} from '../../api/authentication/email_link';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { SignUpRequest } from '../../api/authentication/sign_up';\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nexport class EmailAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n /** @internal */\n readonly _email: string,\n /** @internal */\n readonly _password: string,\n signInMethod: SignInMethod,\n /** @internal */\n readonly _tenantId: string | null = null\n ) {\n super(ProviderId.PASSWORD, signInMethod);\n }\n\n /** @internal */\n static _fromEmailAndPassword(\n email: string,\n password: string\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n password,\n SignInMethod.EMAIL_PASSWORD\n );\n }\n\n /** @internal */\n static _fromEmailAndCode(\n email: string,\n oobCode: string,\n tenantId: string | null = null\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n oobCode,\n SignInMethod.EMAIL_LINK,\n tenantId\n );\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: object | string): EmailAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === SignInMethod.EMAIL_PASSWORD) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n } else if (obj.signInMethod === SignInMethod.EMAIL_LINK) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n\n /** @internal */\n async _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignInWithPasswordRequest = {\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_IN_WITH_PASSWORD,\n signInWithPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLink(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n async _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignUpRequest = {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n linkEmailPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return this._getIdTokenResponse(auth);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performSignInRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithEmailLinkRequest {\n email: string;\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface SignInWithEmailLinkResponse extends IdTokenResponse {\n email: string;\n isNewUser: boolean;\n}\n\nexport async function signInWithEmailLink(\n auth: Auth,\n request: SignInWithEmailLinkRequest\n): Promise<SignInWithEmailLinkResponse> {\n return _performSignInRequest<\n SignInWithEmailLinkRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface SignInWithEmailLinkForLinkingRequest\n extends SignInWithEmailLinkRequest {\n idToken: string;\n}\n\nexport async function signInWithEmailLinkForLinking(\n auth: Auth,\n request: SignInWithEmailLinkForLinkingRequest\n): Promise<SignInWithEmailLinkResponse> {\n return _performSignInRequest<\n SignInWithEmailLinkForLinkingRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithIdpRequest {\n requestUri: string;\n postBody?: string;\n sessionId?: string;\n tenantId?: string;\n returnSecureToken: boolean;\n returnIdpCredential?: boolean;\n idToken?: IdToken;\n autoCreate?: boolean;\n pendingToken?: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithIdpResponse extends IdTokenResponse {\n oauthAccessToken?: string;\n oauthTokenSecret?: string;\n nonce?: string;\n oauthIdToken?: string;\n pendingToken?: string;\n}\n\nexport async function signInWithIdp(\n auth: Auth,\n request: SignInWithIdpRequest\n): Promise<SignInWithIdpResponse> {\n return _performSignInRequest<SignInWithIdpRequest, SignInWithIdpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_IDP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\nexport interface OAuthCredentialParams {\n // OAuth 2 uses either id token or access token\n idToken?: string | null;\n accessToken?: string | null;\n\n // These fields are used with OAuth 1\n oauthToken?: string;\n secret?: string;\n oauthTokenSecret?: string;\n\n // Nonce is only set if pendingToken is not present\n nonce?: string;\n pendingToken?: string;\n\n // Utilities\n providerId: string;\n signInMethod: string;\n}\n\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class OAuthCredential extends AuthCredential {\n /**\n * The OAuth ID token associated with the credential if it belongs to an OIDC provider,\n * such as `google.com`.\n * @readonly\n */\n idToken?: string;\n /**\n * The OAuth access token associated with the credential if it belongs to an\n * {@link OAuthProvider}, such as `facebook.com`, `twitter.com`, etc.\n * @readonly\n */\n accessToken?: string;\n /**\n * The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0\n * provider, such as `twitter.com`.\n * @readonly\n */\n secret?: string;\n\n private nonce?: string;\n private pendingToken: string | null = null;\n\n /** @internal */\n static _fromParams(params: OAuthCredentialParams): OAuthCredential {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n } else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n } else {\n _fail(AuthErrorCode.ARGUMENT_ERROR);\n }\n\n return cred;\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): OAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest }: OAuthCredentialParams = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true\n };\n\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n } else {\n const postBody: Record<string, string> = {};\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\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n\n request.postBody = querystring(postBody);\n }\n\n return request;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _makeTaggedError,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { AuthErrorCode } from '../../core/errors';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { ServerError, ServerErrorMap } from '../errors';\nimport { Auth } from '../../model/public_types';\n\nexport interface SendPhoneVerificationCodeRequest {\n phoneNumber: string;\n recaptchaToken: string;\n tenantId?: string;\n}\n\nexport interface SendPhoneVerificationCodeResponse {\n sessionInfo: string;\n}\n\nexport async function sendPhoneVerificationCode(\n auth: Auth,\n request: SendPhoneVerificationCodeRequest\n): Promise<SendPhoneVerificationCodeResponse> {\n return _performApiRequest<\n SendPhoneVerificationCodeRequest,\n SendPhoneVerificationCodeResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_VERIFICATION_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberRequest {\n temporaryProof?: string;\n phoneNumber?: string;\n sessionInfo?: string;\n code?: string;\n tenantId?: string;\n}\n\nexport interface LinkWithPhoneNumberRequest\n extends SignInWithPhoneNumberRequest {\n idToken: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberResponse extends IdTokenResponse {\n temporaryProof?: string;\n phoneNumber?: string;\n}\n\nexport async function signInWithPhoneNumber(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n return _performSignInRequest<\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function linkWithPhoneNumber(\n auth: Auth,\n request: LinkWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n const response = await _performSignInRequest<\n LinkWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, response);\n }\n return response;\n}\n\ninterface VerifyPhoneNumberForExistingRequest\n extends SignInWithPhoneNumberRequest {\n operation: 'REAUTH';\n}\n\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_: Partial<\n ServerErrorMap<ServerError>\n> = {\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.USER_DELETED\n};\n\nexport async function verifyPhoneNumberForExisting(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise<SignInWithPhoneNumberResponse> {\n const apiRequest: VerifyPhoneNumberForExistingRequest = {\n ...request,\n operation: 'REAUTH'\n };\n return _performSignInRequest<\n VerifyPhoneNumberForExistingRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, apiRequest),\n VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport {\n linkWithPhoneNumber,\n signInWithPhoneNumber,\n SignInWithPhoneNumberRequest,\n verifyPhoneNumberForExisting\n} from '../../api/authentication/sms';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nexport interface PhoneAuthCredentialParameters {\n verificationId?: string;\n verificationCode?: string;\n phoneNumber?: string;\n temporaryProof?: string;\n}\n\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nexport class PhoneAuthCredential extends AuthCredential {\n private constructor(private readonly params: PhoneAuthCredentialParameters) {\n super(ProviderId.PHONE, SignInMethod.PHONE);\n }\n\n /** @internal */\n static _fromVerification(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n\n /** @internal */\n static _fromTokenResponse(\n phoneNumber: string,\n temporaryProof: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return signInWithPhoneNumber(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n return linkWithPhoneNumber(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _makeVerificationRequest(): SignInWithPhoneNumberRequest {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } =\n this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n const obj: Record<string, string> = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n\n return obj;\n }\n\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json: object | string): PhoneAuthCredential | null {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n\n const { verificationId, verificationCode, phoneNumber, temporaryProof } =\n json as { [key: string]: string };\n if (\n !verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof\n ) {\n return null;\n }\n\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extractQuerystring, querystringDecode } from '@firebase/util';\nimport { ActionCodeOperation } from '../model/public_types';\nimport { AuthErrorCode } from './errors';\nimport { _assert } from './util/assert';\n\n/**\n * Enums for fields in URL query string.\n *\n * @enum {string}\n */\nconst enum 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 * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode: string | null): ActionCodeOperation | null {\n switch (mode) {\n case 'recoverEmail':\n return ActionCodeOperation.RECOVER_EMAIL;\n case 'resetPassword':\n return ActionCodeOperation.PASSWORD_RESET;\n case 'signIn':\n return ActionCodeOperation.EMAIL_SIGNIN;\n case 'verifyEmail':\n return ActionCodeOperation.VERIFY_EMAIL;\n case 'verifyAndChangeEmail':\n return ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n case 'revertSecondFactorAddition':\n return ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION;\n default:\n return null;\n }\n}\n\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url: string): string {\n const link = querystringDecode(extractQuerystring(url))['link'];\n\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))[\n 'deep_link_id'\n ];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nexport class ActionCodeURL {\n /**\n * The API key of the email action link.\n */\n readonly apiKey: string;\n /**\n * The action code of the email action link.\n */\n readonly code: string;\n /**\n * The continue URL of the email action link. Null if not provided.\n */\n readonly continueUrl: string | null;\n /**\n * The language code of the email action link. Null if not provided.\n */\n readonly languageCode: string | null;\n /**\n * The action performed by the email action link. It returns from one of the types from\n * {@link ActionCodeInfo}\n */\n readonly operation: string;\n /**\n * The tenant ID of the email action link. Null if the email action is from the parent project.\n */\n readonly tenantId: string | null;\n\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink: string) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[QueryField.API_KEY] ?? null;\n const code = searchParams[QueryField.CODE] ?? null;\n const operation = parseMode(searchParams[QueryField.MODE] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, AuthErrorCode.ARGUMENT_ERROR);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[QueryField.CONTINUE_URL] ?? null;\n this.languageCode = searchParams[QueryField.LANGUAGE_CODE] ?? null;\n this.tenantId = searchParams[QueryField.TENANT_ID] ?? null;\n }\n\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link: string): ActionCodeURL | null {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nexport function parseActionCodeURL(link: string): ActionCodeURL | null {\n return ActionCodeURL.parseLink(link);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\nimport { AuthProvider } from '../../model/public_types';\n\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthCredential } from '../credentials/email';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nexport class EmailAuthProvider implements AuthProvider {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n static readonly PROVIDER_ID: 'password' = ProviderId.PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\n static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password' =\n SignInMethod.EMAIL_PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\n static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink' =\n SignInMethod.EMAIL_LINK;\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n readonly providerId = EmailAuthProvider.PROVIDER_ID;\n\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email: string, password: string): EmailAuthCredential {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(\n email: string,\n emailLink: string\n ): EmailAuthCredential {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, AuthErrorCode.ARGUMENT_ERROR);\n\n return EmailAuthCredential._fromEmailAndCode(\n email,\n actionCodeUrl.code,\n actionCodeUrl.tenantId\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider } from '../../model/public_types';\n\n/**\n * Map of OAuth Custom Parameters.\n *\n * @public\n */\nexport type CustomParameters = Record<string, string>;\n\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nexport abstract class FederatedAuthProvider implements AuthProvider {\n /** @internal */\n defaultLanguageCode: string | null = null;\n /** @internal */\n private customParameters: CustomParameters = {};\n\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(readonly providerId: string) {}\n\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode: string | null): void {\n this.defaultLanguageCode = languageCode;\n }\n\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider {\n this.customParameters = customOAuthParameters;\n return this;\n }\n\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters(): CustomParameters {\n return this.customParameters;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, UserCredential } from '../../model/public_types';\n\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\nimport { OAuthCredential, OAuthCredentialParams } from '../credentials/oauth';\nimport { UserCredentialInternal } from '../../model/user';\nimport { FirebaseError } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { SignInWithIdpResponse } from '../../../internal';\nimport { FederatedAuthProvider } from './federated';\n\n/**\n * Defines the options for initializing an {@link OAuthCredential}.\n *\n * @remarks\n * For ID tokens with nonce claim, the raw nonce has to also be provided.\n *\n * @public\n */\nexport interface OAuthCredentialOptions {\n /**\n * The OAuth ID token used to initialize the {@link OAuthCredential}.\n */\n idToken?: string;\n /**\n * The OAuth access token used to initialize the {@link OAuthCredential}.\n */\n accessToken?: string;\n /**\n * The raw nonce associated with the ID token.\n *\n * @remarks\n * It is required when an ID token with a nonce field is provided. The SHA-256 hash of the\n * raw nonce must match the nonce field in the ID token.\n */\n rawNonce?: string;\n}\n\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nexport abstract class BaseOAuthProvider\n extends FederatedAuthProvider\n implements AuthProvider\n{\n /** @internal */\n private scopes: string[] = [];\n\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope: string): AuthProvider {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes(): string[] {\n return [...this.scopes];\n }\n}\n\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: object | string): OAuthCredential {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert(\n 'providerId' in obj && 'signInMethod' in obj,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return OAuthCredential._fromParams(obj);\n }\n\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params: OAuthCredentialOptions): OAuthCredential {\n return this._credential({ ...params, nonce: params.rawNonce });\n }\n\n /** An internal credential method that accepts more permissive options */\n private _credential(\n params: Omit<OAuthCredentialParams, 'signInMethod' | 'providerId'>\n ): OAuthCredential {\n _assert(params.idToken || params.accessToken, AuthErrorCode.ARGUMENT_ERROR);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static oauthCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce,\n providerId\n } = tokenResponse as SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n\n if (!providerId) {\n return null;\n }\n\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n } catch (e) {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class FacebookAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.FACEBOOK. */\n static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com' =\n SignInMethod.FACEBOOK;\n /** Always set to {@link ProviderId}.FACEBOOK. */\n static readonly PROVIDER_ID: 'facebook.com' = ProviderId.FACEBOOK;\n\n constructor() {\n super(ProviderId.FACEBOOK);\n }\n\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class GoogleAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GOOGLE. */\n static readonly GOOGLE_SIGN_IN_METHOD: 'google.com' = SignInMethod.GOOGLE;\n /** Always set to {@link ProviderId}.GOOGLE. */\n static readonly PROVIDER_ID: 'google.com' = ProviderId.GOOGLE;\n\n constructor() {\n super(ProviderId.GOOGLE);\n this.addScope('profile');\n }\n\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(\n idToken?: string | null,\n accessToken?: string | null\n ): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { oauthIdToken, oauthAccessToken } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class GithubAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GITHUB. */\n static readonly GITHUB_SIGN_IN_METHOD: 'github.com' = SignInMethod.GITHUB;\n /** Always set to {@link ProviderId}.GITHUB. */\n static readonly PROVIDER_ID: 'github.com' = ProviderId.GITHUB;\n\n constructor() {\n super(ProviderId.GITHUB);\n }\n\n /**\n * Creates a credential for Github.\n *\n * @param accessToken - Github access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents the SAML credentials returned by an {@link SAMLAuthProvider}.\n *\n * @public\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\n/**\n * @public\n */\nexport class SAMLAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n providerId: string,\n private readonly pendingToken: string\n ) {\n super(providerId, providerId);\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n signInMethod: this.signInMethod,\n providerId: this.providerId,\n pendingToken: this.pendingToken\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): SAMLAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, pendingToken }: Record<string, string> =\n obj;\n if (\n !providerId ||\n !signInMethod ||\n !pendingToken ||\n providerId !== signInMethod\n ) {\n return null;\n }\n\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n /**\n * Helper static method to avoid exposing the constructor to end users.\n *\n * @internal\n */\n static _create(providerId: string, pendingToken: string): SAMLAuthCredential {\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n return {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true,\n pendingToken: this.pendingToken\n };\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredential } from '../../model/public_types';\nimport { UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { SAMLAuthCredential } from '../credentials/saml';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { FederatedAuthProvider } from './federated';\n\nconst SAML_PROVIDER_PREFIX = 'saml.';\n\n/**\n * An {@link AuthProvider} for SAML.\n *\n * @public\n */\nexport class SAMLAuthProvider extends FederatedAuthProvider {\n /**\n * Constructor. The providerId must start with \"saml.\"\n * @param providerId - SAML provider ID.\n */\n constructor(providerId: string) {\n _assert(\n providerId.startsWith(SAML_PROVIDER_PREFIX),\n AuthErrorCode.ARGUMENT_ERROR\n );\n super(providerId);\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\n * successful SAML flow completes.\n *\n * @remarks\n *\n * For example, to get an {@link AuthCredential}, you could write the\n * following code:\n *\n * ```js\n * const userCredential = await signInWithPopup(auth, samlProvider);\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\n * ```\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n /**\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: string | object): AuthCredential {\n const credential = SAMLAuthCredential.fromJSON(json);\n _assert(credential, AuthErrorCode.ARGUMENT_ERROR);\n return credential;\n }\n\n private static samlCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): SAMLAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { pendingToken, providerId } = tokenResponse as SignInWithIdpResponse;\n\n if (!pendingToken || !providerId) {\n return null;\n }\n\n try {\n return SAMLAuthCredential._create(providerId, pendingToken);\n } catch (e) {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @license\n * Copyright 2020 Twitter LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nexport class TwitterAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.TWITTER. */\n static readonly TWITTER_SIGN_IN_METHOD: 'twitter.com' = SignInMethod.TWITTER;\n /** Always set to {@link ProviderId}.TWITTER. */\n static readonly PROVIDER_ID: 'twitter.com' = ProviderId.TWITTER;\n\n constructor() {\n super(ProviderId.TWITTER);\n }\n\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token: string, secret: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n } catch {\n return null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignUpRequest {\n idToken?: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignUpResponse extends IdTokenResponse {\n displayName?: string;\n email?: string;\n}\n\nexport async function signUp(\n auth: Auth,\n request: SignUpRequest\n): Promise<SignUpResponse> {\n return _performSignInRequest<SignUpRequest, SignUpResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { UserImpl } from './user_impl';\nimport { AuthInternal } from '../../model/auth';\nimport { OperationType, ProviderId } from '../../model/enums';\n\ninterface UserCredentialParams {\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse?: PhoneOrOauthTokenResponse;\n readonly operationType: OperationType;\n}\n\nexport class UserCredentialImpl\n implements UserCredentialInternal, UserCredentialParams\n{\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse: PhoneOrOauthTokenResponse | undefined;\n readonly operationType: OperationType;\n\n constructor(params: UserCredentialParams) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n operationType: OperationType,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise<UserCredentialInternal> {\n const user = await UserImpl._fromIdTokenResponse(\n auth,\n idTokenResponse,\n isAnonymous\n );\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n\n static async _forOperation(\n user: UserInternal,\n operationType: OperationType,\n response: PhoneOrOauthTokenResponse\n ): Promise<UserCredentialImpl> {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\n\nfunction providerIdForResponse(\n response: IdTokenResponse\n): ProviderId | string | null {\n if (response.providerId) {\n return response.providerId;\n }\n\n if ('phoneNumber' in response) {\n return ProviderId.PHONE;\n }\n\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MultiFactorError as MultiFactorErrorPublic } from '../model/public_types';\nimport { FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../model/auth';\nimport { IdTokenResponse } from '../model/id_token';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserInternal } from '../model/user';\nimport { AuthCredential } from '../core/credentials';\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { OperationType } from '../model/enums';\n\nexport type MultiFactorErrorData = MultiFactorErrorPublic['customData'] & {\n _serverResponse: IdTokenMfaResponse;\n};\n\nexport class MultiFactorError\n extends FirebaseError\n implements MultiFactorErrorPublic\n{\n readonly customData: MultiFactorErrorData;\n\n private constructor(\n auth: AuthInternal,\n error: FirebaseError,\n readonly operationType: OperationType,\n readonly user?: UserInternal\n ) {\n super(error.code, error.message);\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, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData!._serverResponse as IdTokenMfaResponse,\n operationType\n };\n }\n\n static _fromErrorAndOperation(\n auth: AuthInternal,\n error: FirebaseError,\n operationType: OperationType,\n user?: UserInternal\n ): MultiFactorError {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\n\nexport function _processCredentialSavingMfaContextIfNecessary(\n auth: AuthInternal,\n operationType: OperationType,\n credential: AuthCredential,\n user?: UserInternal\n): Promise<IdTokenResponse> {\n const idTokenProvider =\n operationType === OperationType.REAUTHENTICATE\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${AuthErrorCode.MFA_REQUIRED}`) {\n throw MultiFactorError._fromErrorAndOperation(\n auth,\n error,\n operationType,\n user\n );\n }\n\n throw error;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ProviderAssociatedObject {\n providerId?: string;\n}\n\n/**\n * Takes a set of UserInfo provider data and converts it to a set of names\n */\nexport function providerDataAsNames<T extends ProviderAssociatedObject>(\n providerData: T[]\n): Set<string> {\n return new Set(\n providerData\n .map(({ providerId }) => providerId)\n .filter(pid => !!pid) as string[]\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport { deleteLinkedAccounts } from '../../api/account_management/account';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { providerDataAsNames } from '../util/providers';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { _reloadWithoutSaving } from './reload';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType, ProviderId } from '../../model/enums';\n\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nexport async function unlink(user: User, providerId: string): Promise<User> {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n\n userInternal.providerData = userInternal.providerData.filter(pd =>\n providersLeft.has(pd.providerId)\n );\n if (!providersLeft.has(ProviderId.PHONE)) {\n userInternal.phoneNumber = null;\n }\n\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\n\nexport async function _link(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredentialInternal> {\n const response = await _logoutIfInvalidated(\n user,\n credential._linkToIdToken(user.auth, await user.getIdToken()),\n bypassAuthState\n );\n return UserCredentialImpl._forOperation(user, OperationType.LINK, response);\n}\n\nexport async function _assertLinkedStatus(\n expected: boolean,\n user: UserInternal,\n provider: string\n): Promise<void> {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n\n const code =\n expected === false\n ? AuthErrorCode.PROVIDER_ALREADY_LINKED\n : AuthErrorCode.NO_SUCH_PROVIDER;\n _assert(providerIds.has(provider) === expected, user.auth, code);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { OperationType } from '../../model/enums';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert, _fail } from '../util/assert';\nimport { _parseToken } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserCredentialImpl } from './user_credential_impl';\n\nexport async function _reauthenticate(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredentialImpl> {\n const { auth } = user;\n const operationType = OperationType.REAUTHENTICATE;\n\n try {\n const response = await _logoutIfInvalidated(\n user,\n _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential,\n user\n ),\n bypassAuthState\n );\n _assert(response.idToken, auth, AuthErrorCode.INTERNAL_ERROR);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, AuthErrorCode.USER_MISMATCH);\n\n return UserCredentialImpl._forOperation(user, operationType, response);\n } catch (e) {\n // Convert user deleted error into user mismatch\n if ((e as FirebaseError)?.code === `auth/${AuthErrorCode.USER_DELETED}`) {\n _fail(auth, AuthErrorCode.USER_MISMATCH);\n }\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential, Auth, User } from '../../model/public_types';\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _assertLinkedStatus, _link } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\n\nexport async function _signInWithCredential(\n auth: AuthInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise<UserCredential> {\n const operationType = OperationType.SIGN_IN;\n const response = await _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential\n );\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n auth,\n operationType,\n response\n );\n\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function signInWithCredential(\n auth: Auth,\n credential: AuthCredential\n): Promise<UserCredential> {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function linkWithCredential(\n user: User,\n credential: AuthCredential\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n\n return _link(userInternal, credential);\n}\n\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\n * or a `TOKEN_EXPIRED` error.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function reauthenticateWithCredential(\n user: User,\n credential: AuthCredential\n): Promise<UserCredential> {\n return _reauthenticate(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, UserCredential } from '../../model/public_types';\n\nimport { signInWithCustomToken as getIdTokenResponse } from '../../api/authentication/custom_token';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Asynchronously signs in using a custom token.\n *\n * @remarks\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\n * be generated by an auth backend using the\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\n *\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\n *\n * @param auth - The {@link Auth} instance.\n * @param customToken - The custom token to sign in with.\n *\n * @public\n */\nexport async function signInWithCustomToken(\n auth: Auth,\n customToken: string\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n const response: IdTokenResponse = await getIdTokenResponse(authInternal, {\n token: customToken,\n returnSecureToken: true\n });\n const cred = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(cred.user);\n return cred;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithCustomTokenRequest {\n token: string;\n returnSecureToken: boolean;\n tenantId?: string;\n}\n\nexport interface SignInWithCustomTokenResponse extends IdTokenResponse {}\n\nexport async function signInWithCustomToken(\n auth: Auth,\n request: SignInWithCustomTokenRequest\n): Promise<SignInWithCustomTokenResponse> {\n return _performSignInRequest<\n SignInWithCustomTokenRequest,\n SignInWithCustomTokenResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FactorId,\n MultiFactorInfo,\n PhoneMultiFactorInfo,\n TotpMultiFactorInfo\n} from '../model/public_types';\nimport {\n PhoneMfaEnrollment,\n MfaEnrollment,\n TotpMfaEnrollment\n} from '../api/account_management/mfa';\nimport { AuthErrorCode } from '../core/errors';\nimport { _fail } from '../core/util/assert';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorInfoImpl implements MultiFactorInfo {\n readonly uid: string;\n readonly displayName?: string | null;\n readonly enrollmentTime: string;\n\n protected constructor(readonly factorId: FactorId, response: MfaEnrollment) {\n this.uid = response.mfaEnrollmentId;\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\n this.displayName = response.displayName;\n }\n\n static _fromServerResponse(\n auth: AuthInternal,\n enrollment: MfaEnrollment\n ): MultiFactorInfoImpl {\n if ('phoneInfo' in enrollment) {\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n } else if ('totpInfo' in enrollment) {\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n }\n return _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n}\n\nexport class PhoneMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements PhoneMultiFactorInfo\n{\n readonly phoneNumber: string;\n\n private constructor(response: PhoneMfaEnrollment) {\n super(FactorId.PHONE, response);\n this.phoneNumber = response.phoneInfo;\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): PhoneMultiFactorInfoImpl {\n return new PhoneMultiFactorInfoImpl(enrollment as PhoneMfaEnrollment);\n }\n}\nexport class TotpMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements TotpMultiFactorInfo\n{\n private constructor(response: TotpMfaEnrollment) {\n super(FactorId.TOTP, response);\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): TotpMultiFactorInfoImpl {\n return new TotpMultiFactorInfoImpl(enrollment as TotpMfaEnrollment);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeSettings, Auth } from '../../model/public_types';\n\nimport { GetOobCodeRequest } from '../../api/authentication/email_and_password';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\nexport function _setActionCodeSettingsOnRequest(\n auth: Auth,\n request: GetOobCodeRequest,\n actionCodeSettings: ActionCodeSettings\n): void {\n _assert(\n actionCodeSettings.url?.length > 0,\n auth,\n AuthErrorCode.INVALID_CONTINUE_URI\n );\n _assert(\n typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\n actionCodeSettings.dynamicLinkDomain.length > 0,\n auth,\n AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN\n );\n\n request.continueUrl = actionCodeSettings.url;\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\n\n if (actionCodeSettings.iOS) {\n _assert(\n actionCodeSettings.iOS.bundleId.length > 0,\n auth,\n AuthErrorCode.MISSING_IOS_BUNDLE_ID\n );\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\n }\n\n if (actionCodeSettings.android) {\n _assert(\n actionCodeSettings.android.packageName.length > 0,\n auth,\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME\n );\n request.androidInstallApp = actionCodeSettings.android.installApp;\n request.androidMinimumVersionCode =\n actionCodeSettings.android.minimumVersion;\n request.androidPackageName = actionCodeSettings.android.packageName;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeInfo,\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as account from '../../api/account_management/email_and_password';\nimport * as authentication from '../../api/authentication/email_and_password';\nimport { signUp, SignUpRequest } from '../../api/authentication/sign_up';\nimport { MultiFactorInfoImpl } from '../../mfa/mfa_info';\nimport { EmailAuthProvider } from '../providers/email';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _assert } from '../util/assert';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { _castAuth } from '../auth/auth_impl';\nimport { AuthErrorCode } from '../errors';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\n\n/**\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\n * cached for the project or tenant.\n *\n * @remarks\n * We only fetch the password policy if the password did not meet policy requirements and\n * there is an existing policy cached. A developer must call validatePassword at least\n * once for the cache to be automatically updated.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @private\n */\nasync function recachePasswordPolicy(auth: Auth): Promise<void> {\n const authInternal = _castAuth(auth);\n if (authInternal._getPasswordPolicyInternal()) {\n await authInternal._updatePasswordPolicy();\n }\n}\n\n/**\n * Sends a password reset email to the given email address. This method does not throw an error when\n * there's no user account with the given email address and\n * [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection) is enabled.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendPasswordResetEmail(\n auth: Auth,\n email: string,\n actionCodeSettings?: ActionCodeSettings\n): Promise<void> {\n const authInternal = _castAuth(auth);\n const request: authentication.PasswordResetRequest = {\n requestType: ActionCodeOperation.PASSWORD_RESET,\n email,\n clientType: RecaptchaClientType.WEB\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\n }\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n authentication.sendPasswordResetEmail\n );\n}\n\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport async function confirmPasswordReset(\n auth: Auth,\n oobCode: string,\n newPassword: string\n): Promise<void> {\n await account\n .resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n })\n .catch(async error => {\n if (\n error.code ===\n `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n // Do not return the email.\n}\n\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function applyActionCode(\n auth: Auth,\n oobCode: string\n): Promise<void> {\n await account.applyActionCode(getModularInstance(auth), { oobCode });\n}\n\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function checkActionCode(\n auth: Auth,\n oobCode: string\n): Promise<ActionCodeInfo> {\n const authModular = getModularInstance(auth);\n const response = await account.resetPassword(authModular, { oobCode });\n\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, AuthErrorCode.INTERNAL_ERROR);\n switch (operation) {\n case ActionCodeOperation.EMAIL_SIGNIN:\n break;\n case ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL:\n _assert(response.newEmail, authModular, AuthErrorCode.INTERNAL_ERROR);\n break;\n case ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION:\n _assert(response.mfaInfo, authModular, AuthErrorCode.INTERNAL_ERROR);\n // fall through\n default:\n _assert(response.email, authModular, AuthErrorCode.INTERNAL_ERROR);\n }\n\n // The multi-factor info for revert second factor addition\n let multiFactorInfo: MultiFactorInfoImpl | null = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(\n _castAuth(authModular),\n response.mfaInfo\n );\n }\n\n return {\n data: {\n email:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.newEmail\n : response.email) || null,\n previousEmail:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nexport async function verifyPasswordResetCode(\n auth: Auth,\n code: string\n): Promise<string> {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email!;\n}\n\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nexport async function createUserWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n const request: SignUpRequest = {\n returnSecureToken: true,\n email,\n password,\n clientType: RecaptchaClientType.WEB\n };\n const signUpResponse: Promise<IdTokenResponse> = handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n signUp\n );\n const response = await signUpResponse.catch(error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(userCredential.user);\n\n return userCredential;\n}\n\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match.\n * When [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection) is enabled,\n * this method fails with \"auth/invalid-credential\" in case of an invalid email/password.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nexport function signInWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise<UserCredential> {\n return signInWithCredential(\n getModularInstance(auth),\n EmailAuthProvider.credential(email, password)\n ).catch(async error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n User\n} from '../../model/public_types';\n\nimport {\n createAuthUri,\n CreateAuthUriRequest\n} from '../../api/authentication/create_auth_uri';\nimport * as api from '../../api/authentication/email_and_password';\nimport { UserInternal } from '../../model/user';\nimport { _getCurrentUrl, _isHttpOrHttps } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Gets the list of possible sign in methods for the given email address. This method returns an\n * empty list when [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection) is enabled, irrespective of the number of\n * authentication methods available for the given email.\n *\n * @remarks\n * This is useful to differentiate methods of sign-in for the same provider, eg.\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\n * {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n *\n * Deprecated. Migrating off of this method is recommended as a security best-practice.\n * Learn more in the Identity Platform documentation for [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection).\n * @public\n */\nexport async function fetchSignInMethodsForEmail(\n auth: Auth,\n email: string\n): Promise<string[]> {\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 const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\n const request: CreateAuthUriRequest = {\n identifier: email,\n continueUri\n };\n\n const { signinMethods } = await createAuthUri(\n getModularInstance(auth),\n request\n );\n\n return signinMethods || [];\n}\n\n/**\n * Sends a verification email to a user.\n *\n * @remarks\n * The verification process is completed by calling {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendEmailVerification(user, actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendEmailVerification(\n user: User,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise<void> {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_EMAIL,\n idToken\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.sendEmailVerification(userInternal.auth, request);\n\n if (email !== user.email) {\n await user.reload();\n }\n}\n\n/**\n * Sends a verification email to a new email address.\n *\n * @remarks\n * The user's email will be updated to the new one after being verified.\n *\n * If you have a custom email action handler, you can complete the verification process by calling\n * {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param newEmail - The new email address to be verified before update.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function verifyBeforeUpdateEmail(\n user: User,\n newEmail: string,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise<void> {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyAndChangeEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n idToken,\n newEmail\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.verifyAndChangeEmail(userInternal.auth, request);\n\n if (email !== user.email) {\n // If the local copy of the email on user is outdated, reload the\n // user.\n await user.reload();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface CreateAuthUriRequest {\n identifier: string;\n continueUri: string;\n tenantId?: string;\n}\n\nexport interface CreateAuthUriResponse {\n signinMethods: string[];\n}\n\nexport async function createAuthUri(\n auth: Auth,\n request: CreateAuthUriRequest\n): Promise<CreateAuthUriResponse> {\n return _performApiRequest<CreateAuthUriRequest, CreateAuthUriResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.CREATE_AUTH_URI,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport {\n updateEmailPassword as apiUpdateEmailPassword,\n UpdateEmailPasswordRequest\n} from '../../api/account_management/email_and_password';\nimport { updateProfile as apiUpdateProfile } from '../../api/account_management/profile';\nimport { UserInternal } from '../../model/user';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Updates a user's profile data.\n *\n * @param user - The user.\n * @param profile - The profile's `displayName` and `photoURL` to update.\n *\n * @public\n */\nexport async function updateProfile(\n user: User,\n {\n displayName,\n photoURL: photoUrl\n }: { displayName?: string | null; photoURL?: string | null }\n): Promise<void> {\n if (displayName === undefined && photoUrl === undefined) {\n return;\n }\n\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await userInternal.getIdToken();\n const profileRequest = {\n idToken,\n displayName,\n photoUrl,\n returnSecureToken: true\n };\n const response = await _logoutIfInvalidated(\n userInternal,\n apiUpdateProfile(userInternal.auth, profileRequest)\n );\n\n userInternal.displayName = response.displayName || null;\n userInternal.photoURL = response.photoUrl || null;\n\n // Update the password provider as well\n const passwordProvider = userInternal.providerData.find(\n ({ providerId }) => providerId === ProviderId.PASSWORD\n );\n if (passwordProvider) {\n passwordProvider.displayName = userInternal.displayName;\n passwordProvider.photoURL = userInternal.photoURL;\n }\n\n await userInternal._updateTokensIfNecessary(response);\n}\n\n/**\n * Updates the user's email address.\n *\n * @remarks\n * An email will be sent to the original email address (if it was set) that allows to revoke the\n * email address change, in order to protect them from account hijacking.\n *\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newEmail - The new email address.\n *\n * Throws \"auth/operation-not-allowed\" error when [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection) is enabled.\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\n *\n * @public\n */\nexport function updateEmail(user: User, newEmail: string): Promise<void> {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n newEmail,\n null\n );\n}\n\n/**\n * Updates the user's password.\n *\n * @remarks\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport function updatePassword(user: User, newPassword: string): Promise<void> {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n null,\n newPassword\n );\n}\n\nasync function updateEmailOrPassword(\n user: UserInternal,\n email: string | null,\n password: string | null\n): Promise<void> {\n const { auth } = user;\n const idToken = await user.getIdToken();\n const request: UpdateEmailPasswordRequest = {\n idToken,\n returnSecureToken: true\n };\n\n if (email) {\n request.email = email;\n }\n\n if (password) {\n request.password = password;\n }\n\n const response = await _logoutIfInvalidated(\n user,\n apiUpdateEmailPassword(auth, request)\n );\n await user._updateTokensIfNecessary(response, /* reload */ true);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface UpdateProfileRequest {\n idToken: string;\n displayName?: string | null;\n photoUrl?: string | null;\n returnSecureToken: boolean;\n}\n\nexport interface UpdateProfileResponse extends IdTokenResponse {\n displayName?: string | null;\n photoUrl?: string | null;\n}\n\nexport async function updateProfile(\n auth: Auth,\n request: UpdateProfileRequest\n): Promise<UpdateProfileResponse> {\n return _performApiRequest<UpdateProfileRequest, UpdateProfileResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n request\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AdditionalUserInfo, UserCredential } from '../../model/public_types';\nimport { IdTokenResponse, IdTokenResponseKind } from '../../model/id_token';\nimport { _parseToken } from './id_token_result';\nimport { UserCredentialInternal } from '../../model/user';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Parse the `AdditionalUserInfo` from the ID token response.\n *\n */\nexport function _fromIdTokenResponse(\n idTokenResponse?: IdTokenResponse\n): AdditionalUserInfo | null {\n if (!idTokenResponse) {\n return null;\n }\n const { providerId } = idTokenResponse;\n const profile = idTokenResponse.rawUserInfo\n ? JSON.parse(idTokenResponse.rawUserInfo)\n : {};\n const isNewUser =\n idTokenResponse.isNewUser ||\n idTokenResponse.kind === IdTokenResponseKind.SignupNewUser;\n if (!providerId && idTokenResponse?.idToken) {\n const signInProvider = _parseToken(idTokenResponse.idToken)?.firebase?.[\n 'sign_in_provider'\n ];\n if (signInProvider) {\n const filteredProviderId =\n signInProvider !== ProviderId.ANONYMOUS &&\n signInProvider !== ProviderId.CUSTOM\n ? (signInProvider as ProviderId)\n : null;\n // Uses generic class in accordance with the legacy SDK.\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\n }\n }\n if (!providerId) {\n return null;\n }\n switch (providerId) {\n case ProviderId.FACEBOOK:\n return new FacebookAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GITHUB:\n return new GithubAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GOOGLE:\n return new GoogleAdditionalUserInfo(isNewUser, profile);\n case ProviderId.TWITTER:\n return new TwitterAdditionalUserInfo(\n isNewUser,\n profile,\n idTokenResponse.screenName || null\n );\n case ProviderId.CUSTOM:\n case ProviderId.ANONYMOUS:\n return new GenericAdditionalUserInfo(isNewUser, null);\n default:\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\n }\n}\n\nclass GenericAdditionalUserInfo implements AdditionalUserInfo {\n constructor(\n readonly isNewUser: boolean,\n readonly providerId: ProviderId | string | null,\n readonly profile: Record<string, unknown> = {}\n ) {}\n}\n\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\n constructor(\n isNewUser: boolean,\n providerId: ProviderId,\n profile: Record<string, unknown>,\n readonly username: string | null\n ) {\n super(isNewUser, providerId, profile);\n }\n}\n\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record<string, unknown>) {\n super(isNewUser, ProviderId.FACEBOOK, profile);\n }\n}\n\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(isNewUser: boolean, profile: Record<string, unknown>) {\n super(\n isNewUser,\n ProviderId.GITHUB,\n profile,\n typeof profile?.login === 'string' ? profile?.login : null\n );\n }\n}\n\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record<string, unknown>) {\n super(isNewUser, ProviderId.GOOGLE, profile);\n }\n}\n\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(\n isNewUser: boolean,\n profile: Record<string, unknown>,\n screenName: string | null\n ) {\n super(isNewUser, ProviderId.TWITTER, profile, screenName);\n }\n}\n\n/**\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\n *\n * @param userCredential - The user credential.\n *\n * @public\n */\nexport function getAdditionalUserInfo(\n userCredential: UserCredential\n): AdditionalUserInfo | null {\n const { user, _tokenResponse } = userCredential as UserCredentialInternal;\n if (user.isAnonymous && !_tokenResponse) {\n // Handle the special case where signInAnonymously() gets called twice.\n // No network call is made so there's nothing to actually fill this in\n return {\n providerId: null,\n isNewUser: false,\n profile: null\n };\n }\n\n return _fromIdTokenResponse(_tokenResponse);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserInternal } from '../model/user';\nimport { MultiFactorSession } from '../model/public_types';\n\nexport const enum MultiFactorSessionType {\n ENROLL = 'enroll',\n SIGN_IN = 'signin'\n}\n\ninterface SerializedMultiFactorSession {\n multiFactorSession: {\n idToken?: string;\n pendingCredential?: string;\n };\n}\n\nexport class MultiFactorSessionImpl implements MultiFactorSession {\n private constructor(\n readonly type: MultiFactorSessionType,\n readonly credential: string,\n readonly user?: UserInternal\n ) {}\n\n static _fromIdtoken(\n idToken: string,\n user?: UserInternal\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.ENROLL,\n idToken,\n user\n );\n }\n\n static _fromMfaPendingCredential(\n mfaPendingCredential: string\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.SIGN_IN,\n mfaPendingCredential\n );\n }\n\n toJSON(): SerializedMultiFactorSession {\n const key =\n this.type === MultiFactorSessionType.ENROLL\n ? 'idToken'\n : 'pendingCredential';\n return {\n multiFactorSession: {\n [key]: this.credential\n }\n };\n }\n\n static fromJSON(\n obj: Partial<SerializedMultiFactorSession>\n ): MultiFactorSessionImpl | null {\n if (obj?.multiFactorSession) {\n if (obj.multiFactorSession?.pendingCredential) {\n return MultiFactorSessionImpl._fromMfaPendingCredential(\n obj.multiFactorSession.pendingCredential\n );\n } else if (obj.multiFactorSession?.idToken) {\n return MultiFactorSessionImpl._fromIdtoken(\n obj.multiFactorSession.idToken\n );\n }\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n MultiFactorResolver,\n UserCredential,\n MultiFactorError\n} from '../model/public_types';\n\nimport { _castAuth } from '../core/auth/auth_impl';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserCredentialImpl } from '../core/user/user_credential_impl';\nimport { _assert, _fail } from '../core/util/assert';\nimport { UserCredentialInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorError as MultiFactorErrorInternal } from './mfa_error';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../model/enums';\n\nexport class MultiFactorResolverImpl implements MultiFactorResolver {\n private constructor(\n readonly session: MultiFactorSessionImpl,\n readonly hints: MultiFactorInfoImpl[],\n private readonly signInResolver: (\n assertion: MultiFactorAssertionImpl\n ) => Promise<UserCredentialInternal>\n ) {}\n\n /** @internal */\n static _fromError(\n authExtern: Auth,\n error: MultiFactorErrorInternal\n ): MultiFactorResolverImpl {\n const auth = _castAuth(authExtern);\n const serverResponse = error.customData._serverResponse;\n const hints = (serverResponse.mfaInfo || []).map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(auth, enrollment)\n );\n\n _assert(\n serverResponse.mfaPendingCredential,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(\n serverResponse.mfaPendingCredential\n );\n\n return new MultiFactorResolverImpl(\n session,\n hints,\n async (\n assertion: MultiFactorAssertionImpl\n ): Promise<UserCredentialInternal> => {\n const mfaResponse = await assertion._process(auth, session);\n // Clear out the unneeded fields from the old login response\n delete serverResponse.mfaInfo;\n delete serverResponse.mfaPendingCredential;\n\n // Use in the new token & refresh token in the old response\n const idTokenResponse = {\n ...serverResponse,\n idToken: mfaResponse.idToken,\n refreshToken: mfaResponse.refreshToken\n };\n\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\n switch (error.operationType) {\n case OperationType.SIGN_IN:\n const userCredential =\n await UserCredentialImpl._fromIdTokenResponse(\n auth,\n error.operationType,\n idTokenResponse\n );\n await auth._updateCurrentUser(userCredential.user);\n return userCredential;\n case OperationType.REAUTHENTICATE:\n _assert(error.user, auth, AuthErrorCode.INTERNAL_ERROR);\n return UserCredentialImpl._forOperation(\n error.user,\n error.operationType,\n idTokenResponse\n );\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n );\n }\n\n async resolveSignIn(\n assertionExtern: MultiFactorAssertionImpl\n ): Promise<UserCredential> {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n return this.signInResolver(assertion);\n }\n}\n\n/**\n * Provides a {@link MultiFactorResolver} suitable for completion of a\n * multi-factor flow.\n *\n * @param auth - The {@link Auth} instance.\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\n * reauthentication operation.\n *\n * @public\n */\nexport function getMultiFactorResolver(\n auth: Auth,\n error: MultiFactorError\n): MultiFactorResolver {\n const authModular = getModularInstance(auth);\n const errorInternal = error as MultiFactorErrorInternal;\n _assert(\n error.customData.operationType,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n errorInternal.customData._serverResponse?.mfaPendingCredential,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n MultiFactorAssertion,\n MultiFactorInfo,\n MultiFactorSession,\n MultiFactorUser,\n User\n} from '../model/public_types';\n\nimport { withdrawMfa } from '../api/account_management/mfa';\nimport { _logoutIfInvalidated } from '../core/user/invalidation';\nimport { UserInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\n\nexport class MultiFactorUserImpl implements MultiFactorUser {\n enrolledFactors: MultiFactorInfo[] = [];\n\n private constructor(readonly user: UserInternal) {\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment)\n );\n }\n });\n }\n\n static _fromUser(user: UserInternal): MultiFactorUserImpl {\n return new MultiFactorUserImpl(user);\n }\n\n async getSession(): Promise<MultiFactorSession> {\n return MultiFactorSessionImpl._fromIdtoken(\n await this.user.getIdToken(),\n this.user\n );\n }\n\n async enroll(\n assertionExtern: MultiFactorAssertion,\n displayName?: string | null\n ): Promise<void> {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n const session = (await this.getSession()) as MultiFactorSessionImpl;\n const finalizeMfaResponse = await _logoutIfInvalidated(\n this.user,\n assertion._process(this.user.auth, session, displayName)\n );\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n\n async unenroll(infoOrUid: MultiFactorInfo | string): Promise<void> {\n const mfaEnrollmentId =\n typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n try {\n const idTokenResponse = await _logoutIfInvalidated(\n this.user,\n withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n })\n );\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(\n ({ uid }) => uid !== mfaEnrollmentId\n );\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n await this.user.reload();\n } catch (e) {\n throw e;\n }\n }\n}\n\nconst multiFactorUserCache = new WeakMap<User, MultiFactorUser>();\n\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nexport function multiFactor(user: User): MultiFactorUser {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(\n userModular,\n MultiFactorUserImpl._fromUser(userModular as UserInternal)\n );\n }\n return multiFactorUserCache.get(userModular)!;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { SignInWithPhoneNumberRequest } from '../authentication/sms';\nimport { FinalizeMfaResponse } from '../authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\n\n/**\n * MFA Info as returned by the API.\n */\ninterface BaseMfaEnrollment {\n mfaEnrollmentId: string;\n enrolledAt: number;\n displayName?: string;\n}\n\n/**\n * An MFA provided by SMS verification.\n */\nexport interface PhoneMfaEnrollment extends BaseMfaEnrollment {\n phoneInfo: string;\n}\n\n/**\n * An MFA provided by TOTP (Time-based One Time Password).\n */\nexport interface TotpMfaEnrollment extends BaseMfaEnrollment {}\n\n/**\n * MfaEnrollment can be any subtype of BaseMfaEnrollment, currently only PhoneMfaEnrollment and TotpMfaEnrollment are supported.\n */\nexport type MfaEnrollment = PhoneMfaEnrollment | TotpMfaEnrollment;\n\nexport interface StartPhoneMfaEnrollmentRequest {\n idToken: string;\n phoneEnrollmentInfo: {\n phoneNumber: string;\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaEnrollmentResponse {\n phoneSessionInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startEnrollPhoneMfa(\n auth: AuthInternal,\n request: StartPhoneMfaEnrollmentRequest\n): Promise<StartPhoneMfaEnrollmentResponse> {\n return _performApiRequest<\n StartPhoneMfaEnrollmentRequest,\n StartPhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaEnrollmentRequest {\n idToken: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollPhoneMfa(\n auth: AuthInternal,\n request: FinalizePhoneMfaEnrollmentRequest\n): Promise<FinalizePhoneMfaEnrollmentResponse> {\n return _performApiRequest<\n FinalizePhoneMfaEnrollmentRequest,\n FinalizePhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface StartTotpMfaEnrollmentRequest {\n idToken: string;\n totpEnrollmentInfo: {};\n tenantId?: string;\n}\n\nexport interface StartTotpMfaEnrollmentResponse {\n totpSessionInfo: {\n sharedSecretKey: string;\n verificationCodeLength: number;\n hashingAlgorithm: string;\n periodSec: number;\n sessionInfo: string;\n finalizeEnrollmentTime: number;\n };\n}\n\nexport function startEnrollTotpMfa(\n auth: AuthInternal,\n request: StartTotpMfaEnrollmentRequest\n): Promise<StartTotpMfaEnrollmentResponse> {\n return _performApiRequest<\n StartTotpMfaEnrollmentRequest,\n StartTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface TotpVerificationInfo {\n sessionInfo: string;\n verificationCode: string;\n}\nexport interface FinalizeTotpMfaEnrollmentRequest {\n idToken: string;\n totpVerificationInfo: TotpVerificationInfo;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizeTotpMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollTotpMfa(\n auth: AuthInternal,\n request: FinalizeTotpMfaEnrollmentRequest\n): Promise<FinalizeTotpMfaEnrollmentResponse> {\n return _performApiRequest<\n FinalizeTotpMfaEnrollmentRequest,\n FinalizeTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface WithdrawMfaRequest {\n idToken: string;\n mfaEnrollmentId: string;\n tenantId?: string;\n}\n\nexport interface WithdrawMfaResponse extends FinalizeMfaResponse {}\n\nexport function withdrawMfa(\n auth: AuthInternal,\n request: WithdrawMfaRequest\n): Promise<WithdrawMfaResponse> {\n return _performApiRequest<WithdrawMfaRequest, WithdrawMfaResponse>(\n auth,\n HttpMethod.POST,\n Endpoint.WITHDRAW_MFA,\n _addTidIfNecessary(auth, request)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Persistence } from '../../model/public_types';\n\nexport const enum PersistenceType {\n SESSION = 'SESSION',\n LOCAL = 'LOCAL',\n NONE = 'NONE'\n}\n\nexport type PersistedBlob = Record<string, unknown>;\n\nexport interface Instantiator<T> {\n (blob: PersistedBlob): T;\n}\n\nexport type PersistenceValue = PersistedBlob | string;\n\nexport const STORAGE_AVAILABLE_KEY = '__sak';\n\nexport interface StorageEventListener {\n (value: PersistenceValue | null): void;\n}\n\nexport interface PersistenceInternal extends Persistence {\n type: PersistenceType;\n _isAvailable(): Promise<boolean>;\n _set(key: string, value: PersistenceValue): Promise<void>;\n _get<T extends PersistenceValue>(key: string): Promise<T | null>;\n _remove(key: string): Promise<void>;\n _addListener(key: string, listener: StorageEventListener): void;\n _removeListener(key: string, listener: StorageEventListener): void;\n // Should this persistence allow migration up the chosen hierarchy?\n _shouldAllowMigration?: boolean;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PersistenceValue,\n STORAGE_AVAILABLE_KEY,\n PersistenceType\n} from '../../core/persistence';\n\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\n\nexport abstract class BrowserPersistenceClass {\n protected constructor(\n protected readonly storageRetriever: () => Storage,\n readonly type: PersistenceType\n ) {}\n\n _isAvailable(): Promise<boolean> {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n _set(key: string, value: PersistenceValue): Promise<void> {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n\n _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n\n _remove(key: string): Promise<void> {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n\n protected get storage(): Storage {\n return this.storageRetriever();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport { getUA } from '@firebase/util';\nimport {\n _isSafari,\n _isIOS,\n _isIframe,\n _isMobileBrowser,\n _isIE10\n} from '../../core/util/browser';\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nfunction _iframeCannotSyncWebStorage(): boolean {\n const ua = getUA();\n return _isSafari(ua) || _isIOS(ua);\n}\n\n// The polling period in case events are not supported\nexport const _POLLING_INTERVAL_MS = 1000;\n\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\nclass BrowserLocalPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'LOCAL' = 'LOCAL';\n\n constructor() {\n super(() => window.localStorage, PersistenceType.LOCAL);\n }\n\n private readonly boundEventHandler = (\n event: StorageEvent,\n poll?: boolean\n ): void => this.onStorageEvent(event, poll);\n private readonly listeners: Record<string, Set<StorageEventListener>> = {};\n private readonly localCache: Record<string, string | null> = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n\n // Safari or iOS browser and embedded in an iframe.\n private readonly safariLocalStorageNotSynced =\n _iframeCannotSyncWebStorage() && _isIframe();\n // Whether to use polling instead of depending on window events\n private readonly fallbackToPolling = _isMobileBrowser();\n readonly _shouldAllowMigration = true;\n\n private forAllChangedKeys(\n cb: (key: string, oldValue: string | null, newValue: string | null) => void\n ): void {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n\n private onStorageEvent(event: StorageEvent, poll = false): void {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys(\n (key: string, _oldValue: string | null, newValue: string | null) => {\n this.notifyListeners(key, newValue);\n }\n );\n return;\n }\n\n const key = event.key;\n\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n\n // Safari embedded iframe. Storage event will trigger with the delta\n // changes but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced) {\n // Get current iframe page value.\n const storedValue = this.storage.getItem(key);\n // Value not synchronized, synchronize manually.\n if (event.newValue !== storedValue) {\n if (event.newValue !== null) {\n // Value changed from current value.\n this.storage.setItem(key, event.newValue);\n } else {\n // Current value deleted.\n this.storage.removeItem(key);\n }\n } else if (this.localCache[key] === event.newValue && !poll) {\n // Already detected and processed, do not trigger listeners again.\n return;\n }\n }\n\n const triggerListeners = (): void => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\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 this.notifyListeners(key, storedValue);\n };\n\n const storedValue = this.storage.getItem(key);\n if (\n _isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue\n ) {\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\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n }\n\n private notifyListeners(key: string, value: string | null): void {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys(\n (key: string, oldValue: string | null, newValue: string | null) => {\n this.onStorageEvent(\n new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }),\n /* poll */ true\n );\n }\n );\n }, _POLLING_INTERVAL_MS);\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n private attachListener(): void {\n window.addEventListener('storage', this.boundEventHandler);\n }\n\n private detachListener(): void {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in 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 if (this.fallbackToPolling) {\n this.startPolling();\n } else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n\n // Update local cache on base operations:\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const value = await super._get<T>(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n\n async _remove(key: string): Promise<void> {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserLocalPersistence: Persistence = BrowserLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nclass BrowserSessionPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'SESSION' = 'SESSION';\n\n constructor() {\n super(() => window.sessionStorage, PersistenceType.SESSION);\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserSessionPersistence: Persistence = BrowserSessionPersistence;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ReceiverHandler,\n _EventType,\n _ReceiverResponse,\n SenderMessageEvent,\n _Status,\n _SenderRequest\n} from './index';\nimport { _allSettled } from './promise';\n\n/**\n * Interface class for receiving messages.\n *\n */\nexport class Receiver {\n private static readonly receivers: Receiver[] = [];\n private readonly boundEventHandler: EventListener;\n\n private readonly handlersMap: {\n // Typescript doesn't have existential types :(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [eventType: string]: Set<ReceiverHandler<any, any>>;\n } = {};\n\n constructor(private readonly eventTarget: EventTarget) {\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget: EventTarget): Receiver {\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 const existingInstance = this.receivers.find(receiver =>\n receiver.isListeningto(eventTarget)\n );\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n\n private isListeningto(eventTarget: EventTarget): boolean {\n return this.eventTarget === eventTarget;\n }\n\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n private async handleEvent<\n T extends _ReceiverResponse,\n S extends _SenderRequest\n >(event: Event): Promise<void> {\n const messageEvent = event as MessageEvent<SenderMessageEvent<S>>;\n const { eventId, eventType, data } = messageEvent.data;\n\n const handlers: Set<ReceiverHandler<T, S>> | undefined =\n this.handlersMap[eventType];\n if (!handlers?.size) {\n return;\n }\n\n messageEvent.ports[0].postMessage({\n status: _Status.ACK,\n eventId,\n eventType\n });\n\n const promises = Array.from(handlers).map(async handler =>\n handler(messageEvent.origin, data)\n );\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: _Status.DONE,\n eventId,\n eventType,\n response\n });\n }\n\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n eventHandler: ReceiverHandler<T, S>\n ): void {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n\n this.handlersMap[eventType].add(eventHandler);\n }\n\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n eventHandler?: ReceiverHandler<T, S>\n ): void {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** TODO: remove this once tslib has a polyfill for Promise.allSettled */\ninterface PromiseFulfilledResult<T> {\n fulfilled: true;\n value: T;\n}\n\ninterface PromiseRejectedResult {\n fulfilled: false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any;\n}\n\nexport type PromiseSettledResult<T> =\n | PromiseFulfilledResult<T>\n | PromiseRejectedResult;\n\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nexport function _allSettled<T>(\n promises: Array<Promise<T>>\n): Promise<Array<PromiseSettledResult<T>>> {\n return Promise.all(\n promises.map(async promise => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n } as PromiseFulfilledResult<T>;\n } catch (reason) {\n return {\n fulfilled: false,\n reason\n } as PromiseRejectedResult;\n }\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _generateEventId(prefix = '', digits = 10): string {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _generateEventId } from '../../core/util/event_id';\nimport {\n _SenderRequest,\n _EventType,\n ReceiverMessageEvent,\n _MessageError,\n SenderMessageEvent,\n _Status,\n _ReceiverMessageResponse,\n _ReceiverResponse,\n _TimeoutDuration\n} from './index';\n\ninterface MessageHandler {\n messageChannel: MessageChannel;\n onMessage: EventListenerOrEventListenerObject;\n}\n\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nexport class Sender {\n private readonly handlers = new Set<MessageHandler>();\n\n constructor(private readonly target: ServiceWorker) {}\n\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n private removeMessageHandler(handler: MessageHandler): void {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener(\n 'message',\n handler.onMessage\n );\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send<T extends _ReceiverResponse, S extends _SenderRequest>(\n eventType: _EventType,\n data: S,\n timeout = _TimeoutDuration.ACK\n ): Promise<_ReceiverMessageResponse<T>> {\n const messageChannel =\n typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(_MessageError.CONNECTION_UNAVAILABLE);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer: any;\n let handler: MessageHandler;\n return new Promise<_ReceiverMessageResponse<T>>((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(_MessageError.UNSUPPORTED_EVENT));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event: Event): void {\n const messageEvent = event as MessageEvent<ReceiverMessageEvent<T>>;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case _Status.ACK:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(_MessageError.TIMEOUT));\n }, _TimeoutDuration.COMPLETION);\n break;\n case _Status.DONE:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(_MessageError.INVALID_RESPONSE));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage(\n {\n eventType,\n eventId,\n data\n } as SenderMessageEvent<S>,\n [messageChannel.port2]\n );\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\n }\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Recaptcha, GreCAPTCHATopLevel } from './recaptcha/recaptcha';\n\n/**\n * A specialized window type that melds the normal window type plus the\n * various bits we need. The three different blocks that are &'d together\n * cant be defined in the same block together.\n */\nexport type AuthWindow = {\n // Standard window types\n [T in keyof Window]: Window[T];\n} & {\n // Any known / named properties we want to add\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n ___jsl?: Record<string, any>;\n gapi?: typeof gapi;\n} & {\n // A final catch-all for callbacks (which will have random names) that\n // we will stick on the window.\n [callback: string]: (...args: unknown[]) => void;\n};\n\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nexport function _window(): AuthWindow {\n return window as unknown as AuthWindow;\n}\n\nexport function _setWindowLocation(url: string): void {\n _window().location.href = url;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _window } from '../auth_window';\n\nexport function _isWorker(): boolean {\n return (\n typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function'\n );\n}\n\nexport async function _getActiveServiceWorker(): Promise<ServiceWorker | null> {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n } catch {\n return null;\n }\n}\n\nexport function _getServiceWorkerController(): ServiceWorker | null {\n return navigator?.serviceWorker?.controller || null;\n}\n\nexport function _getWorkerGlobalScope(): ServiceWorker | null {\n return _isWorker() ? (self as unknown as ServiceWorker) : null;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\nimport {\n PersistedBlob,\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener,\n STORAGE_AVAILABLE_KEY\n} from '../../core/persistence/';\nimport {\n _EventType,\n _PingResponse,\n KeyChangedResponse,\n KeyChangedRequest,\n PingRequest,\n _TimeoutDuration\n} from '../messagechannel/index';\nimport { Receiver } from '../messagechannel/receiver';\nimport { Sender } from '../messagechannel/sender';\nimport {\n _isWorker,\n _getActiveServiceWorker,\n _getServiceWorkerController,\n _getWorkerGlobalScope\n} from '../util/worker';\n\nexport const DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n\ninterface DBObject {\n [DB_DATA_KEYPATH]: string;\n value: PersistedBlob;\n}\n\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6\n *\n */\nclass DBPromise<T> {\n constructor(private readonly request: IDBRequest) {}\n\n toPromise(): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\n\nfunction getObjectStore(db: IDBDatabase, isReadWrite: boolean): IDBObjectStore {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\n\nexport async function _clearDatabase(db: IDBDatabase): Promise<void> {\n const objectStore = getObjectStore(db, true);\n return new DBPromise<void>(objectStore.clear()).toPromise();\n}\n\nexport function _deleteDatabase(): Promise<void> {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise<void>(request).toPromise();\n}\n\nexport function _openDatabase(): Promise<IDBDatabase> {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n } catch (e) {\n reject(e);\n }\n });\n\n request.addEventListener('success', async () => {\n const db: IDBDatabase = request.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\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n } else {\n resolve(db);\n }\n });\n });\n}\n\nexport async function _putObject(\n db: IDBDatabase,\n key: string,\n value: PersistenceValue | string\n): Promise<void> {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise<void>(request).toPromise();\n}\n\nasync function getObject(\n db: IDBDatabase,\n key: string\n): Promise<PersistedBlob | null> {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise<DBObject | undefined>(request).toPromise();\n return data === undefined ? null : data.value;\n}\n\nexport function _deleteObject(db: IDBDatabase, key: string): Promise<void> {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise<void>(request).toPromise();\n}\n\nexport const _POLLING_INTERVAL_MS = 800;\nexport const _TRANSACTION_RETRY_COUNT = 3;\n\nclass IndexedDBLocalPersistence implements InternalPersistence {\n static type: 'LOCAL' = 'LOCAL';\n\n type = PersistenceType.LOCAL;\n db?: IDBDatabase;\n readonly _shouldAllowMigration = true;\n\n private readonly listeners: Record<string, Set<StorageEventListener>> = {};\n private readonly localCache: Record<string, PersistenceValue | null> = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n private pendingWrites = 0;\n\n private receiver: Receiver | null = null;\n private sender: Sender | null = null;\n private serviceWorkerReceiverAvailable = false;\n private activeServiceWorker: ServiceWorker | null = null;\n // Visible for testing only\n readonly _workerInitializationPromise: Promise<void>;\n\n constructor() {\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(\n () => {},\n () => {}\n );\n }\n\n async _openDb(): Promise<IDBDatabase> {\n if (this.db) {\n return this.db;\n }\n this.db = await _openDatabase();\n return this.db;\n }\n\n async _withRetries<T>(op: (db: IDBDatabase) => Promise<T>): Promise<T> {\n let numAttempts = 0;\n\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n } catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.db) {\n this.db.close();\n this.db = undefined;\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n private async initializeServiceWorkerMessaging(): Promise<void> {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n\n /**\n * As the worker we should listen to events from the main window.\n */\n private async initializeReceiver(): Promise<void> {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope()!);\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\n _EventType.KEY_CHANGED,\n async (_origin: string, data: KeyChangedRequest) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n }\n );\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\n _EventType.PING,\n async (_origin: string, _data: PingRequest) => {\n return [_EventType.KEY_CHANGED];\n }\n );\n }\n\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n private async initializeSender(): Promise<void> {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send<_PingResponse, PingRequest>(\n _EventType.PING,\n {},\n _TimeoutDuration.LONG_ACK\n );\n if (!results) {\n return;\n }\n if (\n results[0]?.fulfilled &&\n results[0]?.value.includes(_EventType.KEY_CHANGED)\n ) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n private async notifyServiceWorker(key: string): Promise<void> {\n if (\n !this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker\n ) {\n return;\n }\n try {\n await this.sender._send<KeyChangedResponse, KeyChangedRequest>(\n _EventType.KEY_CHANGED,\n { key },\n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? _TimeoutDuration.LONG_ACK\n : _TimeoutDuration.ACK\n );\n } catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n\n async _isAvailable(): Promise<boolean> {\n try {\n if (!indexedDB) {\n return false;\n }\n const db = await _openDatabase();\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n return true;\n } catch {}\n return false;\n }\n\n private async _withPendingWrite(write: () => Promise<void>): Promise<void> {\n this.pendingWrites++;\n try {\n await write();\n } finally {\n this.pendingWrites--;\n }\n }\n\n async _set(key: string, value: PersistenceValue): Promise<void> {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n\n async _get<T extends PersistenceValue>(key: string): Promise<T | null> {\n const obj = (await this._withRetries((db: IDBDatabase) =>\n getObject(db, key)\n )) as T;\n this.localCache[key] = obj;\n return obj;\n }\n\n async _remove(key: string): Promise<void> {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n\n private async _poll(): Promise<string[]> {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db: IDBDatabase) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise<DBObject[] | null>(getAllRequest).toPromise();\n });\n\n if (!result) {\n return [];\n }\n\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n\n const keys = [];\n const keysInResult = new Set();\n if (result.length !== 0) {\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value as PersistenceValue);\n keys.push(key);\n }\n }\n }\n\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n\n private notifyListeners(\n key: string,\n newValue: PersistenceValue | null\n ): void {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(\n async () => this._poll(),\n _POLLING_INTERVAL_MS\n );\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n }\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nexport const indexedDBLocalPersistence: Persistence = IndexedDBLocalPersistence;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport { RecaptchaParameters } from '../../model/public_types';\nimport {\n Recaptcha,\n GreCAPTCHATopLevel,\n GreCAPTCHARenderOption,\n GreCAPTCHA\n} from './recaptcha';\n\nexport const _SOLVE_TIME_MS = 500;\nexport const _EXPIRATION_TIME_MS = 60_000;\nexport const _WIDGET_ID_START = 1_000_000_000_000;\n\nexport interface Widget {\n getResponse: () => string | null;\n delete: () => void;\n execute: () => void;\n}\n\nexport class MockReCaptcha implements Recaptcha {\n private counter = _WIDGET_ID_START;\n _widgets = new Map<number, Widget>();\n\n constructor(private readonly auth: AuthInternal) {}\n\n render(\n container: string | HTMLElement,\n parameters?: RecaptchaParameters\n ): number {\n const id = this.counter;\n this._widgets.set(\n id,\n new MockWidget(container, this.auth.name, parameters || {})\n );\n this.counter++;\n return id;\n }\n\n reset(optWidgetId?: number): void {\n const id = optWidgetId || _WIDGET_ID_START;\n void this._widgets.get(id)?.delete();\n this._widgets.delete(id);\n }\n\n getResponse(optWidgetId?: number): string {\n const id = optWidgetId || _WIDGET_ID_START;\n return this._widgets.get(id)?.getResponse() || '';\n }\n\n async execute(optWidgetId?: number | string): Promise<string> {\n const id: number = (optWidgetId as number) || _WIDGET_ID_START;\n void this._widgets.get(id)?.execute();\n return '';\n }\n}\n\nexport class MockGreCAPTCHATopLevel implements GreCAPTCHATopLevel {\n enterprise: GreCAPTCHA = new MockGreCAPTCHA();\n ready(callback: () => void): void {\n callback();\n }\n\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey: string,\n _options: { action: string }\n ): Promise<string> {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container: string | HTMLElement,\n _parameters: GreCAPTCHARenderOption\n ): string {\n return '';\n }\n}\n\nexport class MockGreCAPTCHA implements GreCAPTCHA {\n ready(callback: () => void): void {\n callback();\n }\n\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey: string,\n _options: { action: string }\n ): Promise<string> {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container: string | HTMLElement,\n _parameters: GreCAPTCHARenderOption\n ): string {\n return '';\n }\n}\n\nexport class MockWidget {\n private readonly container: HTMLElement;\n private readonly isVisible: boolean;\n private timerId: number | null = null;\n private deleted = false;\n private responseToken: string | null = null;\n private readonly clickHandler = (): void => {\n this.execute();\n };\n\n constructor(\n containerOrId: string | HTMLElement,\n appName: string,\n private readonly params: RecaptchaParameters\n ) {\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, AuthErrorCode.ARGUMENT_ERROR, { appName });\n\n this.container = container;\n this.isVisible = this.params.size !== 'invisible';\n if (this.isVisible) {\n this.execute();\n } else {\n this.container.addEventListener('click', this.clickHandler);\n }\n }\n\n getResponse(): string | null {\n this.checkIfDeleted();\n return this.responseToken;\n }\n\n delete(): void {\n this.checkIfDeleted();\n this.deleted = true;\n if (this.timerId) {\n clearTimeout(this.timerId);\n this.timerId = null;\n }\n this.container.removeEventListener('click', this.clickHandler);\n }\n\n execute(): void {\n this.checkIfDeleted();\n if (this.timerId) {\n return;\n }\n\n this.timerId = window.setTimeout(() => {\n this.responseToken = generateRandomAlphaNumericString(50);\n const { callback, 'expired-callback': expiredCallback } = this.params;\n if (callback) {\n try {\n callback(this.responseToken);\n } catch (e) {}\n }\n\n this.timerId = window.setTimeout(() => {\n this.timerId = null;\n this.responseToken = null;\n if (expiredCallback) {\n try {\n expiredCallback();\n } catch (e) {}\n }\n\n if (this.isVisible) {\n this.execute();\n }\n }, _EXPIRATION_TIME_MS);\n }, _SOLVE_TIME_MS);\n }\n\n private checkIfDeleted(): void {\n if (this.deleted) {\n throw new Error('reCAPTCHA mock was already deleted!');\n }\n }\n}\n\nfunction generateRandomAlphaNumericString(len: number): string {\n const chars = [];\n const allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < len; i++) {\n chars.push(\n allowedChars.charAt(Math.floor(Math.random() * allowedChars.length))\n );\n }\n return chars.join('');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as jsHelpers from '../load_js';\nimport { Recaptcha, isV2 } from './recaptcha';\nimport { MockReCaptcha } from './recaptcha_mock';\n\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nexport const _JSLOAD_CALLBACK = jsHelpers._generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\n\n/**\n * We need to mark this interface as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport interface ReCaptchaLoader {\n load(auth: AuthInternal, hl?: string): Promise<Recaptcha>;\n clearedOneInstance(): void;\n}\n\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nexport class ReCaptchaLoaderImpl implements ReCaptchaLoader {\n private hostLanguage = '';\n private counter = 0;\n /**\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\n * `window.grecaptcha.render()` will not. Another load will add it.\n */\n private readonly librarySeparatelyLoaded = !!_window().grecaptcha?.render;\n\n load(auth: AuthInternal, hl = ''): Promise<Recaptcha> {\n _assert(isHostLanguageValid(hl), auth, AuthErrorCode.ARGUMENT_ERROR);\n\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\n return Promise.resolve(_window().grecaptcha! as Recaptcha);\n }\n return new Promise<Recaptcha>((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, NETWORK_TIMEOUT_DELAY.get());\n\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n\n const recaptcha = _window().grecaptcha as Recaptcha;\n\n if (!recaptcha || !isV2(recaptcha)) {\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n return;\n }\n\n // Wrap the greptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n\n const url = `${jsHelpers._recaptchaV2ScriptUrl()}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n\n jsHelpers._loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n });\n });\n }\n\n clearedOneInstance(): void {\n this.counter--;\n }\n\n private shouldResolveImmediately(hl: string): boolean {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (\n !!_window().grecaptcha?.render &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded)\n );\n }\n}\n\nfunction isHostLanguageValid(hl: string): boolean {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\n\nexport class MockReCaptchaLoaderImpl implements ReCaptchaLoader {\n async load(auth: AuthInternal): Promise<Recaptcha> {\n return new MockReCaptcha(auth);\n }\n\n clearedOneInstance(): void {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, RecaptchaParameters } from '../../model/public_types';\nimport { getRecaptchaParams } from '../../api/authentication/recaptcha';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { _isHttpOrHttps } from '../../core/util/location';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport { _isWorker } from '../util/worker';\nimport { Recaptcha } from './recaptcha';\nimport {\n MockReCaptchaLoaderImpl,\n ReCaptchaLoader,\n ReCaptchaLoaderImpl\n} from './recaptcha_loader';\n\nexport const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\n\nconst DEFAULT_PARAMS: RecaptchaParameters = {\n theme: 'light',\n type: 'image'\n};\n\ntype TokenCallback = (token: string) => void;\n\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @remarks\n * `RecaptchaVerifier` does not work in a Node.js environment.\n *\n * @public\n */\nexport class RecaptchaVerifier implements ApplicationVerifierInternal {\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n readonly type = RECAPTCHA_VERIFIER_TYPE;\n private destroyed = false;\n private widgetId: number | null = null;\n private readonly container: HTMLElement;\n private readonly isInvisible: boolean;\n private readonly tokenChangeListeners = new Set<TokenCallback>();\n private renderPromise: Promise<number> | null = null;\n private readonly auth: AuthInternal;\n\n /** @internal */\n readonly _recaptchaLoader: ReCaptchaLoader;\n private recaptcha: Recaptcha | null = null;\n\n /**\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n */\n constructor(\n authExtern: Auth,\n containerOrId: HTMLElement | string,\n private readonly parameters: RecaptchaParameters = {\n ...DEFAULT_PARAMS\n }\n ) {\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify(): Promise<string> {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n\n return new Promise<string>(resolve => {\n const tokenChange = (token: string): void => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render(): Promise<number> {\n try {\n this.assertNotDestroyed();\n } catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n\n if (this.renderPromise) {\n return this.renderPromise;\n }\n\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n\n return this.renderPromise;\n }\n\n /** @internal */\n _reset(): void {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear(): void {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n\n private validateStartingState(): void {\n _assert(!this.parameters.sitekey, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n this.isInvisible || !this.container.hasChildNodes(),\n this.auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n }\n\n private makeTokenCallback(\n existing: TokenCallback | string | undefined\n ): TokenCallback {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n } else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n\n private assertNotDestroyed(): void {\n _assert(!this.destroyed, this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n\n private async makeRenderPromise(): Promise<number> {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n\n this.widgetId = this.getAssertedRecaptcha().render(\n container,\n this.parameters\n );\n }\n\n return this.widgetId;\n }\n\n private async init(): Promise<void> {\n _assert(\n _isHttpOrHttps() && !_isWorker(),\n this.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(\n this.auth,\n this.auth.languageCode || undefined\n );\n\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.parameters.sitekey = siteKey;\n }\n\n private getAssertedRecaptcha(): Recaptcha {\n _assert(this.recaptcha, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.recaptcha;\n }\n}\n\nfunction domReady(): Promise<void> {\n let resolver: (() => void) | null = null;\n return new Promise<void>(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n\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 = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n\n throw e;\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ApplicationVerifier,\n Auth,\n ConfirmationResult,\n PhoneInfoOptions,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { startEnrollPhoneMfa } from '../../api/account_management/mfa';\nimport { startSignInPhoneMfa } from '../../api/authentication/mfa';\nimport { sendPhoneVerificationCode } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assertLinkedStatus, _link } from '../../core/user/link_unlink';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport {\n linkWithCredential,\n reauthenticateWithCredential,\n signInWithCredential\n} from '../../core/strategies/credential';\nimport {\n MultiFactorSessionImpl,\n MultiFactorSessionType\n} from '../../mfa/mfa_session';\nimport { UserInternal } from '../../model/user';\nimport { RECAPTCHA_VERIFIER_TYPE } from '../recaptcha/recaptcha_verifier';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\ninterface OnConfirmationCallback {\n (credential: PhoneAuthCredential): Promise<UserCredential>;\n}\n\nclass ConfirmationResultImpl implements ConfirmationResult {\n constructor(\n readonly verificationId: string,\n private readonly onConfirmation: OnConfirmationCallback\n ) {}\n\n confirm(verificationCode: string): Promise<UserCredential> {\n const authCredential = PhoneAuthCredential._fromVerification(\n this.verificationId,\n verificationCode\n );\n return this.onConfirmation(authCredential);\n }\n}\n\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function signInWithPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(\n authInternal,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n signInWithCredential(authInternal, cred)\n );\n}\n\n/**\n * Links the user account with the given phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function linkWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(false, userInternal, ProviderId.PHONE);\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n linkWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function reauthenticateWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise<ConfirmationResult> {\n const userInternal = getModularInstance(user) as UserInternal;\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n reauthenticateWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nexport async function _verifyPhoneNumber(\n auth: AuthInternal,\n options: PhoneInfoOptions | string,\n verifier: ApplicationVerifierInternal\n): Promise<string> {\n const recaptchaToken = await verifier.verify();\n\n try {\n _assert(\n typeof recaptchaToken === 'string',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n verifier.type === RECAPTCHA_VERIFIER_TYPE,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n let phoneInfoOptions: PhoneInfoOptions;\n\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n } else {\n phoneInfoOptions = options;\n }\n\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session as MultiFactorSessionImpl;\n\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(\n session.type === MultiFactorSessionType.ENROLL,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollPhoneMfa(auth, {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n }\n });\n return response.phoneSessionInfo.sessionInfo;\n } else {\n _assert(\n session.type === MultiFactorSessionType.SIGN_IN,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const mfaEnrollmentId =\n phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, AuthErrorCode.MISSING_MFA_INFO);\n const response = await startSignInPhoneMfa(auth, {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n recaptchaToken\n }\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n } else {\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n });\n return sessionInfo;\n }\n } finally {\n verifier._reset();\n }\n}\n\n/**\n * Updates the user's phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nexport async function updatePhoneNumber(\n user: User,\n credential: PhoneAuthCredential\n): Promise<void> {\n await _link(getModularInstance(user) as UserInternal, credential);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from '../account_management/mfa';\nimport { SignInWithIdpResponse } from './idp';\nimport {\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n} from './sms';\n\nexport interface FinalizeMfaResponse {\n idToken: string;\n refreshToken: string;\n}\n\n/**\n * @internal\n */\nexport interface IdTokenMfaResponse extends IdTokenResponse {\n mfaPendingCredential?: string;\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface StartPhoneMfaSignInRequest {\n mfaPendingCredential: string;\n mfaEnrollmentId: string;\n phoneSignInInfo: {\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaSignInResponse {\n phoneResponseInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startSignInPhoneMfa(\n auth: Auth,\n request: StartPhoneMfaSignInRequest\n): Promise<StartPhoneMfaSignInResponse> {\n return _performApiRequest<\n StartPhoneMfaSignInRequest,\n StartPhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaSignInRequest {\n mfaPendingCredential: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n tenantId?: string;\n}\n\n// TOTP MFA Sign in only has a finalize phase. Phone MFA has a start phase to initiate sending an\n// SMS and a finalize phase to complete sign in. With TOTP, the user already has the OTP in the\n// TOTP/Authenticator app.\nexport interface FinalizeTotpMfaSignInRequest {\n mfaPendingCredential: string;\n totpVerificationInfo: { verificationCode: string };\n tenantId?: string;\n mfaEnrollmentId: string;\n}\n\nexport interface FinalizePhoneMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport interface FinalizeTotpMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport function finalizeSignInPhoneMfa(\n auth: Auth,\n request: FinalizePhoneMfaSignInRequest\n): Promise<FinalizePhoneMfaSignInResponse> {\n return _performApiRequest<\n FinalizePhoneMfaSignInRequest,\n FinalizePhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport function finalizeSignInTotpMfa(\n auth: Auth,\n request: FinalizeTotpMfaSignInRequest\n): Promise<FinalizeTotpMfaSignInResponse> {\n return _performApiRequest<\n FinalizeTotpMfaSignInRequest,\n FinalizeTotpMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport type PhoneOrOauthTokenResponse =\n | SignInWithPhoneNumberResponse\n | SignInWithIdpResponse\n | IdTokenResponse;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n PhoneInfoOptions,\n ApplicationVerifier,\n UserCredential\n} from '../../model/public_types';\n\nimport { SignInWithPhoneNumberResponse } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal as ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal as AuthInternal } from '../../model/auth';\nimport { UserCredentialInternal as UserCredentialInternal } from '../../model/user';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { _verifyPhoneNumber } from '../strategies/phone';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthCredential } from '../../core';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @remarks\n * `PhoneAuthProvider` does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nexport class PhoneAuthProvider {\n /** Always set to {@link ProviderId}.PHONE. */\n static readonly PROVIDER_ID: 'phone' = ProviderId.PHONE;\n /** Always set to {@link SignInMethod}.PHONE. */\n static readonly PHONE_SIGN_IN_METHOD: 'phone' = SignInMethod.PHONE;\n\n /** Always set to {@link ProviderId}.PHONE. */\n readonly providerId = PhoneAuthProvider.PROVIDER_ID;\n private readonly auth: AuthInternal;\n\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth: Auth) {\n this.auth = _castAuth(auth);\n }\n\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - For abuse prevention, this method also requires a\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\n * {@link RecaptchaVerifier}.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow..\n */\n verifyPhoneNumber(\n phoneOptions: PhoneInfoOptions | string,\n applicationVerifier: ApplicationVerifier\n ): Promise<string> {\n return _verifyPhoneNumber(\n this.auth,\n phoneOptions,\n getModularInstance(applicationVerifier as ApplicationVerifierInternal)\n );\n }\n\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return PhoneAuthCredential._fromVerification(\n verificationId,\n verificationCode\n );\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n const credential = userCredential as UserCredentialInternal;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return PhoneAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): AuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } =\n tokenResponse as SignInWithPhoneNumberResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(\n phoneNumber,\n temporaryProof\n );\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PopupRedirectResolver } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { _getInstance } from './instantiator';\n\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nexport function _withDefaultResolver(\n auth: AuthInternal,\n resolverOverride: PopupRedirectResolver | undefined\n): PopupRedirectResolverInternal {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n\n _assert(auth._popupRedirectResolver, auth, AuthErrorCode.ARGUMENT_ERROR);\n\n return auth._popupRedirectResolver;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _link as _linkUser } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { _assert } from '../util/assert';\nimport { _signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { ProviderId } from '../../model/enums';\n\nexport interface IdpTaskParams {\n auth: AuthInternal;\n requestUri: string;\n sessionId?: string;\n tenantId?: string;\n postBody?: string;\n pendingToken?: string;\n user?: UserInternal;\n bypassAuthState?: boolean;\n}\n\nexport type IdpTask = (\n params: IdpTaskParams\n) => Promise<UserCredentialInternal>;\n\nclass IdpCredential extends AuthCredential {\n constructor(readonly params: IdpTaskParams) {\n super(ProviderId.CUSTOM, ProviderId.CUSTOM);\n }\n\n _getIdTokenResponse(auth: AuthInternal): Promise<PhoneOrOauthTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise<IdTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n\n _getReauthenticationResolver(auth: AuthInternal): Promise<IdTokenResponse> {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n private _buildIdpRequest(idToken?: string): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n\n if (idToken) {\n request.idToken = idToken;\n }\n\n return request;\n }\n}\n\nexport function _signIn(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n return _signInWithCredential(\n params.auth,\n new IdpCredential(params),\n params.bypassAuthState\n ) as Promise<UserCredentialInternal>;\n}\n\nexport function _reauth(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _reauthenticate(\n user,\n new IdpCredential(params),\n params.bypassAuthState\n );\n}\n\nexport async function _link(\n params: IdpTaskParams\n): Promise<UserCredentialInternal> {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _linkUser(user, new IdpCredential(params), params.bypassAuthState);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { debugAssert, _fail } from '../util/assert';\nimport {\n _link,\n _reauth,\n _signIn,\n IdpTask,\n IdpTaskParams\n} from '../strategies/idp';\nimport { AuthInternal } from '../../model/auth';\n\ninterface PendingPromise {\n resolve: (cred: UserCredentialInternal | null) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nexport abstract class AbstractPopupRedirectOperation\n implements AuthEventConsumer\n{\n private pendingPromise: PendingPromise | null = null;\n private eventManager: EventManager | null = null;\n readonly filter: AuthEventType[];\n\n abstract eventId: string | null;\n\n constructor(\n protected readonly auth: AuthInternal,\n filter: AuthEventType | AuthEventType[],\n protected readonly resolver: PopupRedirectResolverInternal,\n protected user?: UserInternal,\n protected readonly bypassAuthState = false\n ) {\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n\n abstract onExecution(): Promise<void>;\n\n execute(): Promise<UserCredentialInternal | null> {\n return new Promise<UserCredentialInternal | null>(\n async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n } catch (e) {\n this.reject(e as Error);\n }\n }\n );\n }\n\n async onAuthEvent(event: AuthEvent): Promise<void> {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n\n const params: IdpTaskParams = {\n auth: this.auth,\n requestUri: urlResponse!,\n sessionId: sessionId!,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n\n try {\n this.resolve(await this.getIdpTask(type)(params));\n } catch (e) {\n this.reject(e as Error);\n }\n }\n\n onError(error: FirebaseError): void {\n this.reject(error);\n }\n\n private getIdpTask(type: AuthEventType): IdpTask {\n switch (type) {\n case AuthEventType.SIGN_IN_VIA_POPUP:\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n return _signIn;\n case AuthEventType.LINK_VIA_POPUP:\n case AuthEventType.LINK_VIA_REDIRECT:\n return _link;\n case AuthEventType.REAUTH_VIA_POPUP:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return _reauth;\n default:\n _fail(this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n protected resolve(cred: UserCredentialInternal | null): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n\n protected reject(error: Error): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n\n private unregisterAndCleanUp(): void {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n\n this.pendingPromise = null;\n this.cleanUp();\n }\n\n abstract cleanUp(): void;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _assert,\n debugAssert,\n _createError,\n _assertInstanceOf\n} from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport { AuthPopup } from '../util/popup';\nimport { AbstractPopupRedirectOperation } from '../../core/strategies/abstract_popup_redirect_operation';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/*\n * The event timeout is the same on mobile and desktop, no need for Delay. Set this to 8s since\n * blocking functions can take upto 7s to complete sign in, as documented in:\n * https://cloud.google.com/identity-platform/docs/blocking-functions#understanding_blocking_functions\n * https://firebase.google.com/docs/auth/extend-with-blocking-functions#understanding_blocking_functions\n */\nexport const enum _Timeout {\n AUTH_EVENT = 8000\n}\nexport const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function signInWithPopup(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(\n authInternal,\n AuthEventType.SIGN_IN_VIA_POPUP,\n provider,\n resolverInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function reauthenticateWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.REAUTH_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function linkWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.LINK_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n // Only one popup is ever shown at once. The lifecycle of the current popup\n // can be managed / cancelled by the constructor.\n private static currentPopupAction: PopupOperation | null = null;\n private authWindow: AuthPopup | null = null;\n private pollId: number | null = null;\n\n constructor(\n auth: AuthInternal,\n filter: AuthEventType,\n private readonly provider: AuthProvider,\n resolver: PopupRedirectResolverInternal,\n user?: UserInternal\n ) {\n super(auth, filter, resolver, user);\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n\n PopupOperation.currentPopupAction = this;\n }\n\n async executeNotNull(): Promise<UserCredential> {\n const result = await this.execute();\n _assert(result, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return result;\n }\n\n async onExecution(): Promise<void> {\n debugAssert(\n this.filter.length === 1,\n 'Popup operations only handle one event'\n );\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(\n this.auth,\n this.provider,\n this.filter[0], // There's always one, see constructor\n eventId\n );\n this.authWindow.associatedEvent = eventId;\n\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(\n _createError(this.auth, AuthErrorCode.WEB_STORAGE_UNSUPPORTED)\n );\n }\n });\n\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n\n get eventId(): string | null {\n return this.authWindow?.associatedEvent || null;\n }\n\n cancel(): void {\n this.reject(_createError(this.auth, AuthErrorCode.EXPIRED_POPUP_REQUEST));\n }\n\n cleanUp(): void {\n if (this.authWindow) {\n this.authWindow.close();\n }\n\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n\n private pollUserCancellation(): void {\n const poll = (): void => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight. This is specifically true for\n // Firefox or if the opener is in an iframe, in which case the oauth\n // helper closes the popup.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(\n _createError(this.auth, AuthErrorCode.POPUP_CLOSED_BY_USER)\n );\n }, _Timeout.AUTH_EVENT);\n return;\n }\n\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n\n poll();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserCredentialInternal } from '../../model/user';\nimport { PersistenceInternal } from '../persistence';\nimport { _persistenceKeyName } from '../persistence/persistence_user_manager';\nimport { _getInstance } from '../util/instantiator';\nimport { AbstractPopupRedirectOperation } from './abstract_popup_redirect_operation';\n\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap: Map<\n string,\n () => Promise<UserCredentialInternal | null>\n> = new Map();\n\nexport class RedirectAction extends AbstractPopupRedirectOperation {\n eventId = null;\n\n constructor(\n auth: AuthInternal,\n resolver: PopupRedirectResolverInternal,\n bypassAuthState = false\n ) {\n super(\n auth,\n [\n AuthEventType.SIGN_IN_VIA_REDIRECT,\n AuthEventType.LINK_VIA_REDIRECT,\n AuthEventType.REAUTH_VIA_REDIRECT,\n AuthEventType.UNKNOWN\n ],\n resolver,\n undefined,\n bypassAuthState\n );\n }\n\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute(): Promise<UserCredentialInternal | null> {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(\n this.resolver,\n this.auth\n );\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n } catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n\n return readyOutcome();\n }\n\n async onAuthEvent(event: AuthEvent): Promise<void> {\n if (event.type === AuthEventType.SIGN_IN_VIA_REDIRECT) {\n return super.onAuthEvent(event);\n } else if (event.type === AuthEventType.UNKNOWN) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n } else {\n this.resolve(null);\n }\n }\n }\n\n async onExecution(): Promise<void> {}\n\n cleanUp(): void {}\n}\n\nexport async function _getAndClearPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise<boolean> {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\n\nexport async function _setPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise<void> {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\n\nexport function _clearRedirectOutcomes(): void {\n redirectOutcomeMap.clear();\n}\n\nexport function _overrideRedirectResult(\n auth: AuthInternal,\n result: () => Promise<UserCredentialInternal | null>\n): void {\n redirectOutcomeMap.set(auth._key(), result);\n}\n\nfunction resolverPersistence(\n resolver: PopupRedirectResolverInternal\n): PersistenceInternal {\n return _getInstance(resolver._redirectPersistence);\n}\n\nfunction pendingRedirectKey(auth: AuthInternal): string {\n return _persistenceKeyName(\n PENDING_REDIRECT_KEY,\n auth.config.apiKey,\n auth.name\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { _assertLinkedStatus } from '../../core/user/link_unlink';\nimport { _assertInstanceOf } from '../../core/util/assert';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport {\n RedirectAction,\n _setPendingRedirectStatus\n} from '../../core/strategies/redirect';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link signInWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _signInWithRedirect(auth, provider, resolver) as Promise<never>;\n}\n\nexport async function _signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await authInternal._initializationPromise;\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n\n return resolverInternal._openRedirect(\n authInternal,\n provider,\n AuthEventType.SIGN_IN_VIA_REDIRECT\n );\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link reauthenticateWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Reauthenticate using a redirect.\n * await reauthenticateWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _reauthenticateWithRedirect(\n user,\n provider,\n resolver\n ) as Promise<never>;\n}\nexport async function _reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.REAUTH_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link linkWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<never> {\n return _linkWithRedirect(user, provider, resolver) as Promise<never>;\n}\nexport async function _linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise<void | never> {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.LINK_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns `null`.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function getRedirectResult(\n auth: Auth,\n resolver?: PopupRedirectResolver\n): Promise<UserCredential | null> {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\n\nexport async function _getRedirectResult(\n auth: Auth,\n resolverExtern?: PopupRedirectResolver,\n bypassAuthState = false\n): Promise<UserCredential | null> {\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user as UserInternal);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n\n return result;\n}\n\nasync function prepareUserForRedirect(user: UserInternal): Promise<string> {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager\n} from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { AuthInternal } from '../../model/auth';\nimport { _createError } from '../util/assert';\n\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\n\nexport class AuthEventManager implements EventManager {\n private readonly cachedEventUids: Set<string> = new Set();\n private readonly consumers: Set<AuthEventConsumer> = new Set();\n protected queuedRedirectEvent: AuthEvent | null = null;\n protected hasHandledPotentialRedirect = false;\n private lastProcessedEventTime = Date.now();\n\n constructor(private readonly auth: AuthInternal) {}\n\n registerConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.add(authEventConsumer);\n\n if (\n this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)\n ) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n\n unregisterConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.delete(authEventConsumer);\n }\n\n onEvent(event: AuthEvent): boolean {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n\n this.hasHandledPotentialRedirect = true;\n\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n\n return handled;\n }\n\n private sendToConsumer(event: AuthEvent, consumer: AuthEventConsumer): void {\n if (event.error && !isNullRedirectEvent(event)) {\n const code =\n (event.error.code?.split('auth/')[1] as AuthErrorCode) ||\n AuthErrorCode.INTERNAL_ERROR;\n consumer.onError(_createError(this.auth, code));\n } else {\n consumer.onAuthEvent(event);\n }\n }\n\n private isEventForConsumer(\n event: AuthEvent,\n consumer: AuthEventConsumer\n ): boolean {\n const eventIdMatches =\n consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n\n private hasEventBeenHandled(event: AuthEvent): boolean {\n if (\n Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS\n ) {\n this.cachedEventUids.clear();\n }\n\n return this.cachedEventUids.has(eventUid(event));\n }\n\n private saveEventToCache(event: AuthEvent): void {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\n\nfunction eventUid(e: AuthEvent): string {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\n\nfunction isNullRedirectEvent({ type, error }: AuthEvent): boolean {\n return (\n type === AuthEventType.UNKNOWN &&\n error?.code === `auth/${AuthErrorCode.NO_AUTH_EVENT}`\n );\n}\n\nfunction isRedirectEvent(event: AuthEvent): boolean {\n switch (event.type) {\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n case AuthEventType.LINK_VIA_REDIRECT:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return true;\n case AuthEventType.UNKNOWN:\n return isNullRedirectEvent(event);\n default:\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _performApiRequest, Endpoint, HttpMethod } from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface GetProjectConfigRequest {\n androidPackageName?: string;\n iosBundleId?: string;\n}\n\nexport interface GetProjectConfigResponse {\n authorizedDomains: string[];\n}\n\nexport async function _getProjectConfig(\n auth: Auth,\n request: GetProjectConfigRequest = {}\n): Promise<GetProjectConfigResponse> {\n return _performApiRequest<GetProjectConfigRequest, GetProjectConfigResponse>(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PROJECT_CONFIG,\n request\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProjectConfig } from '../../api/project_config/get_project_config';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from './assert';\nimport { _getCurrentUrl } from './location';\n\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\n\nexport async function _validateOrigin(auth: AuthInternal): Promise<void> {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n\n const { authorizedDomains } = await _getProjectConfig(auth);\n\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n } catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, AuthErrorCode.INVALID_ORIGIN);\n}\n\nfunction matchDomain(expected: string): boolean {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (\n protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', '')\n );\n }\n\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n\n if (IP_ADDRESS_REGEX.test(expected)) {\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 hostname === expected;\n }\n\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',\n 'i'\n );\n return re.test(hostname);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as js from '../load_js';\n\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\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 */\nfunction resetUnloadedGapiModules(): void {\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 const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(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];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\n\nfunction loadGapi(auth: AuthInternal): Promise<gapi.iframes.Context> {\n return new Promise<gapi.iframes.Context>((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe(): void {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\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 resetUnloadedGapiModules();\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n } else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\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 const cbName = js._generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n } else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }\n };\n // Load GApi loader.\n return js\n ._loadJS(`${js._gapiScriptUrl()}?onload=${cbName}`)\n .catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\n\nlet cachedGApiLoader: Promise<gapi.iframes.Context> | null = null;\nexport function _loadGapi(auth: AuthInternal): Promise<gapi.iframes.Context> {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\nexport function _resetLoader(): void {\n cachedGApiLoader = null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { querystring } from '@firebase/util';\nimport { DefaultConfig } from '../../../internal';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _emulatorUrl } from '../../core/util/emulator';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as gapiLoader from './gapi';\n\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\n\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [DefaultConfig.API_HOST, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\n\nfunction getIframeUrl(auth: AuthInternal): string {\n const config = auth.config;\n _assert(config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n\n const params: Record<string, string> = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\n\nexport async function _openIframe(\n auth: AuthInternal\n): Promise<gapi.iframes.Iframe> {\n const context = await gapiLoader._loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, AuthErrorCode.INTERNAL_ERROR);\n return context.open(\n {\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n },\n (iframe: gapi.iframes.Iframe) =>\n new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n\n const networkError = _createError(\n auth,\n AuthErrorCode.NETWORK_REQUEST_FAILED\n );\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve(): void {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\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(clearTimerAndResolve, () => {\n reject(networkError);\n });\n })\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport {\n _isChromeIOS,\n _isFirefox,\n _isIOSStandalone\n} from '../../core/util/browser';\nimport { AuthInternal } from '../../model/auth';\n\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\n\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\n\nconst FIREFOX_EMPTY_URL = 'http://localhost';\n\nexport class AuthPopup {\n associatedEvent: string | null = null;\n\n constructor(readonly window: Window | null) {}\n\n close(): void {\n if (this.window) {\n try {\n this.window.close();\n } catch (e) {}\n }\n }\n}\n\nexport function _open(\n auth: AuthInternal,\n url?: string,\n name?: string,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n): AuthPopup {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n\n const options: { [key: string]: string } = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\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 const ua = getUA().toLowerCase();\n\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\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 = 'yes';\n }\n\n const optionsString = Object.entries(options).reduce(\n (accum, [key, value]) => `${accum}${key}=${value},`,\n ''\n );\n\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, AuthErrorCode.POPUP_BLOCKED);\n\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n\n return new AuthPopup(newWin);\n}\n\nfunction openAsNewWindowIOS(url: string, target: string): void {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 1,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 1,\n null\n );\n el.dispatchEvent(click);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { AuthProvider } from '../../model/public_types';\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { isEmpty, querystring } from '@firebase/util';\nimport { _emulatorUrl } from './emulator';\nimport { FederatedAuthProvider } from '../providers/federated';\nimport { BaseOAuthProvider } from '../providers/oauth';\n\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n\n/**\n * Fragment name for the App Check token that gets passed to the widget\n *\n * @internal\n */\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ntype WidgetParams = {\n apiKey: ApiKey;\n appName: AppName;\n authType: AuthEventType;\n redirectUrl?: string;\n v: string;\n providerId?: string;\n scopes?: string;\n customParameters?: string;\n eventId?: string;\n tid?: string;\n} & { [key: string]: string | undefined };\n\nexport async function _getRedirectUrl(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n redirectUrl?: string,\n eventId?: string,\n additionalParams?: Record<string, string>\n): Promise<string> {\n _assert(auth.config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n _assert(auth.config.apiKey, auth, AuthErrorCode.INVALID_API_KEY);\n\n const params: WidgetParams = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n\n // TODO: maybe set eid as endipointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n\n const paramsDict = params as Record<string, string | number>;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n\n // Sets the App Check token to pass to the widget\n const appCheckToken = await auth._getAppCheckToken();\n const appCheckTokenFragment = appCheckToken\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\n : '';\n\n // Start at index 1 to skip the leading '&' in the query string\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(\n 1\n )}${appCheckTokenFragment}`;\n}\n\nfunction getHandlerBase({ config }: AuthInternal): string {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, PopupRedirectResolver } from '../model/public_types';\n\nimport { AuthEventManager } from '../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../core/errors';\nimport { _assert, debugAssert, _fail } from '../core/util/assert';\nimport { _generateEventId } from '../core/util/event_id';\nimport { _getCurrentUrl } from '../core/util/location';\nimport { _validateOrigin } from '../core/util/validate_origin';\nimport { AuthInternal } from '../model/auth';\nimport {\n AuthEventType,\n EventManager,\n GapiAuthEvent,\n GapiOutcome,\n PopupRedirectResolverInternal\n} from '../model/popup_redirect';\nimport { _setWindowLocation } from './auth_window';\nimport { _openIframe } from './iframe/iframe';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { _open, AuthPopup } from './util/popup';\nimport { _getRedirectResult } from './strategies/redirect';\nimport { _getRedirectUrl } from '../core/util/handler';\nimport { _isIOS, _isMobileBrowser, _isSafari } from '../core/util/browser';\nimport { _overrideRedirectResult } from '../core/strategies/redirect';\n\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\n\ninterface WebStorageSupportMessage extends gapi.iframes.Message {\n [index: number]: Record<string, boolean>;\n}\n\ninterface ManagerOrPromise {\n manager?: EventManager;\n promise?: Promise<EventManager>;\n}\n\nclass BrowserPopupRedirectResolver implements PopupRedirectResolverInternal {\n private readonly eventManagers: Record<string, ManagerOrPromise> = {};\n private readonly iframes: Record<string, gapi.iframes.Iframe> = {};\n private readonly originValidationPromises: Record<string, Promise<void>> = {};\n\n readonly _redirectPersistence = browserSessionPersistence;\n\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<AuthPopup> {\n debugAssert(\n this.eventManagers[auth._key()]?.manager,\n '_initialize() not called before _openPopup()'\n );\n\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n return _open(auth, url, _generateEventId());\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<never> {\n await this._originValidation(auth);\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n _setWindowLocation(url);\n return new Promise(() => {});\n }\n\n _initialize(auth: AuthInternal): Promise<EventManager> {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n } else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n\n return promise;\n }\n\n private async initAndGetManager(auth: AuthInternal): Promise<EventManager> {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register<GapiAuthEvent>(\n 'authEvent',\n (iframeEvent: GapiAuthEvent | null) => {\n _assert(iframeEvent?.authEvent, auth, AuthErrorCode.INVALID_AUTH_EVENT);\n // TODO: Consider splitting redirect and popup events earlier on\n\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? GapiOutcome.ACK : GapiOutcome.ERROR };\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n\n _isIframeWebStorageSupported(\n auth: AuthInternal,\n cb: (supported: boolean) => unknown\n ): void {\n const iframe = this.iframes[auth._key()];\n iframe.send<gapi.iframes.Message, WebStorageSupportMessage>(\n WEB_STORAGE_SUPPORT_KEY,\n { type: WEB_STORAGE_SUPPORT_KEY },\n result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n }\n\n _originValidation(auth: AuthInternal): Promise<void> {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n get _shouldInitProactively(): boolean {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n\n _completeRedirectFn = _getRedirectResult;\n\n _overrideRedirectResult = _overrideRedirectResult;\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @public\n */\nexport const browserPopupRedirectResolver: PopupRedirectResolver =\n BrowserPopupRedirectResolver;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n FactorId,\n PhoneMultiFactorAssertion\n} from '../../../model/public_types';\n\nimport { MultiFactorAssertionImpl } from '../../../mfa/mfa_assertion';\nimport { AuthInternal } from '../../../model/auth';\nimport { finalizeEnrollPhoneMfa } from '../../../api/account_management/mfa';\nimport { PhoneAuthCredential } from '../../../core/credentials/phone';\nimport {\n finalizeSignInPhoneMfa,\n FinalizeMfaResponse\n} from '../../../api/authentication/mfa';\n\n/**\n * {@inheritdoc PhoneMultiFactorAssertion}\n *\n * @public\n */\nexport class PhoneMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements PhoneMultiFactorAssertion\n{\n private constructor(private readonly credential: PhoneAuthCredential) {\n super(FactorId.PHONE);\n }\n\n /** @internal */\n static _fromCredential(\n credential: PhoneAuthCredential\n ): PhoneMultiFactorAssertionImpl {\n return new PhoneMultiFactorAssertionImpl(credential);\n }\n\n /** @internal */\n _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise<FinalizeMfaResponse> {\n return finalizeEnrollPhoneMfa(auth, {\n idToken,\n displayName,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise<FinalizeMfaResponse> {\n return finalizeSignInPhoneMfa(auth, {\n mfaPendingCredential,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n}\n\n/**\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\n *\n * @public\n */\nexport class PhoneMultiFactorGenerator {\n private constructor() {}\n\n /**\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}\n */\n static assertion(credential: PhoneAuthCredential): PhoneMultiFactorAssertion {\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\n }\n\n /**\n * The identifier of the phone second factor: `phone`.\n */\n static FACTOR_ID = 'phone';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FactorId, MultiFactorAssertion } from '../model/public_types';\nimport { debugFail } from '../core/util/assert';\nimport { MultiFactorSessionImpl, MultiFactorSessionType } from './mfa_session';\nimport { FinalizeMfaResponse } from '../api/authentication/mfa';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorAssertionImpl implements MultiFactorAssertion {\n protected constructor(readonly factorId: FactorId) {}\n\n _process(\n auth: AuthInternal,\n session: MultiFactorSessionImpl,\n displayName?: string | null\n ): Promise<FinalizeMfaResponse> {\n switch (session.type) {\n case MultiFactorSessionType.ENROLL:\n return this._finalizeEnroll(auth, session.credential, displayName);\n case MultiFactorSessionType.SIGN_IN:\n return this._finalizeSignIn(auth, session.credential);\n default:\n return debugFail('unexpected MultiFactorSessionType');\n }\n }\n\n abstract _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise<FinalizeMfaResponse>;\n abstract _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise<FinalizeMfaResponse>;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Unsubscribe } from '@firebase/util';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\n\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\ninterface TokenListener {\n (tok: string | null): unknown;\n}\n\nexport class AuthInterop implements FirebaseAuthInternal {\n private readonly internalListeners: Map<TokenListener, Unsubscribe> =\n new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n getUid(): string | null {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n\n async getToken(\n forceRefresh?: boolean\n ): Promise<{ accessToken: string } | null> {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n\n addAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(\n (user as UserInternal | null)?.stsTokenManager.accessToken || null\n );\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n\n removeAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n\n private assertAuthConfigured(): void {\n _assert(\n this.auth._initializationPromise,\n AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n );\n }\n\n private updateProactiveRefresh(): void {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n } else {\n this.auth._stopProactiveRefresh();\n }\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\n\nimport {\n initializeAuth,\n beforeAuthStateChanged,\n onIdTokenChanged,\n connectAuthEmulator\n} from '..';\nimport { registerAuth } from '../core/auth/register';\nimport { ClientPlatform } from '../core/util/version';\nimport { browserLocalPersistence } from './persistence/local_storage';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { indexedDBLocalPersistence } from './persistence/indexed_db';\nimport { browserPopupRedirectResolver } from './popup_redirect';\nimport { Auth, User } from '../model/public_types';\nimport { getDefaultEmulatorHost, getExperimentalSetting } from '@firebase/util';\nimport { _setExternalJSProvider } from './load_js';\nimport { _createError } from '../core/util/assert';\nimport { AuthErrorCode } from '../core/errors';\n\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\nconst authIdTokenMaxAge =\n getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\n\nlet lastPostedIdToken: string | undefined | null = null;\n\nconst mintCookieFactory = (url: string) => async (user: User | null) => {\n const idTokenResult = user && (await user.getIdTokenResult());\n const idTokenAge =\n idTokenResult &&\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1_000;\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\n return;\n }\n // Specifically trip null => undefined when logged out, to delete any existing cookie\n const idToken = idTokenResult?.token;\n if (lastPostedIdToken === idToken) {\n return;\n }\n lastPostedIdToken = idToken;\n await fetch(url, {\n method: idToken ? 'POST' : 'DELETE',\n headers: idToken\n ? {\n 'Authorization': `Bearer ${idToken}`\n }\n : {}\n });\n};\n\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nexport function getAuth(app: FirebaseApp = getApp()): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n\n const auth = initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n\n const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');\n if (authTokenSyncUrl) {\n const mintCookie = mintCookieFactory(authTokenSyncUrl);\n beforeAuthStateChanged(auth, mintCookie, () =>\n mintCookie(auth.currentUser)\n );\n onIdTokenChanged(auth, user => mintCookie(user));\n }\n\n const authEmulatorHost = getDefaultEmulatorHost('auth');\n if (authEmulatorHost) {\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\n }\n\n return auth;\n}\n\nfunction getScriptParentElement(): HTMLDocument | HTMLHeadElement {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n\n_setExternalJSProvider({\n loadJS(url: string): Promise<Event> {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(AuthErrorCode.INTERNAL_ERROR);\n error.customData = e as unknown as Record<string, unknown>;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n },\n\n gapiScript: 'https://apis.google.com/js/api.js',\n recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',\n recaptchaEnterpriseScript:\n 'https://www.google.com/recaptcha/enterprise.js?render='\n});\n\nregisterAuth(ClientPlatform.BROWSER);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\n\nimport { name, version } from '../../../package.json';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _getClientVersion, ClientPlatform } from '../util/version';\nimport { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';\nimport { AuthInterop } from './firebase_internal';\nimport { ConfigInternal } from '../../model/auth';\nimport { Dependencies } from '../../model/public_types';\nimport { _initializeAuthInstance } from './initialize';\n\nexport const enum _ComponentName {\n AUTH = 'auth',\n AUTH_INTERNAL = 'auth-internal'\n}\n\nfunction getVersionForPlatform(\n clientPlatform: ClientPlatform\n): string | undefined {\n switch (clientPlatform) {\n case ClientPlatform.NODE:\n return 'node';\n case ClientPlatform.REACT_NATIVE:\n return 'rn';\n case ClientPlatform.WORKER:\n return 'webworker';\n case ClientPlatform.CORDOVA:\n return 'cordova';\n case ClientPlatform.WEB_EXTENSION:\n return 'web-extension';\n default:\n return undefined;\n }\n}\n\n/** @internal */\nexport function registerAuth(clientPlatform: ClientPlatform): void {\n _registerComponent(\n new Component(\n _ComponentName.AUTH,\n (container, { options: deps }: { options?: Dependencies }) => {\n const app = container.getProvider('app').getImmediate()!;\n const heartbeatServiceProvider =\n container.getProvider<'heartbeat'>('heartbeat');\n const appCheckServiceProvider =\n container.getProvider<'app-check-internal'>('app-check-internal');\n const { apiKey, authDomain } = app.options;\n\n _assert(\n apiKey && !apiKey.includes(':'),\n AuthErrorCode.INVALID_API_KEY,\n { appName: app.name }\n );\n\n const config: ConfigInternal = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: DefaultConfig.API_HOST,\n tokenApiHost: DefaultConfig.TOKEN_API_HOST,\n apiScheme: DefaultConfig.API_SCHEME,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n\n const authInstance = new AuthImpl(\n app,\n heartbeatServiceProvider,\n appCheckServiceProvider,\n config\n );\n _initializeAuthInstance(authInstance, deps);\n\n return authInstance;\n },\n ComponentType.PUBLIC\n )\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback(\n (container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\n _ComponentName.AUTH_INTERNAL\n );\n authInternalProvider.initialize();\n }\n )\n );\n\n _registerComponent(\n new Component(\n _ComponentName.AUTH_INTERNAL,\n container => {\n const auth = _castAuth(\n container.getProvider(_ComponentName.AUTH).getImmediate()!\n );\n return (auth => new AuthInterop(auth))(auth);\n },\n ComponentType.PRIVATE\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface CordovaWindow extends Window {\n cordova: {\n plugins: {\n browsertab: {\n isAvailable(cb: (available: boolean) => void): void;\n openUrl(url: string): void;\n close(): void;\n };\n };\n\n InAppBrowser: {\n open(url: string, target: string, options: string): InAppBrowserRef;\n };\n };\n\n universalLinks: {\n subscribe(\n n: null,\n cb: (event: Record<string, string> | null) => void\n ): void;\n };\n\n BuildInfo: {\n readonly packageName: string;\n readonly displayName: string;\n };\n\n handleOpenURL(url: string): void;\n}\n\nexport interface InAppBrowserRef {\n close?: () => void;\n}\n\nexport function _cordovaWindow(): CordovaWindow {\n return window as unknown as CordovaWindow;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp } from '@firebase/app';\nimport { deepEqual } from '@firebase/util';\nimport { Auth, Dependencies } from '../../model/public_types';\n\nimport { AuthErrorCode } from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport { _fail } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { AuthImpl } from './auth_impl';\n\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nexport function initializeAuth(app: FirebaseApp, deps?: Dependencies): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n const auth = provider.getImmediate() as AuthImpl;\n const initialOptions = provider.getOptions() as Dependencies;\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n } else {\n _fail(auth, AuthErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const auth = provider.initialize({ options: deps }) as AuthImpl;\n\n return auth;\n}\n\nexport function _initializeAuthInstance(\n auth: AuthImpl,\n deps?: Dependencies\n): void {\n const persistence = deps?.persistence || [];\n const hierarchy = (\n Array.isArray(persistence) ? persistence : [persistence]\n ).map<PersistenceInternal>(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider } from '../../model/public_types';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n debugAssert,\n _assert,\n _createError,\n _fail\n} from '../../core/util/assert';\nimport { _isAndroid, _isIOS, _isIOS7Or8 } from '../../core/util/browser';\nimport { _getRedirectUrl } from '../../core/util/handler';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthEvent } from '../../model/popup_redirect';\nimport { InAppBrowserRef, _cordovaWindow } from '../plugins';\nimport {\n GetProjectConfigRequest,\n _getProjectConfig\n} from '../../api/project_config/get_project_config';\n\n/**\n * How long to wait after the app comes back into focus before concluding that\n * the user closed the sign in tab.\n */\nconst REDIRECT_TIMEOUT_MS = 2000;\n\n/**\n * Generates the URL for the OAuth handler.\n */\nexport async function _generateHandlerUrl(\n auth: AuthInternal,\n event: AuthEvent,\n provider: AuthProvider\n): Promise<string> {\n // Get the cordova plugins\n const { BuildInfo } = _cordovaWindow();\n debugAssert(event.sessionId, 'AuthEvent did not contain a session ID');\n const sessionDigest = await computeSha256(event.sessionId);\n\n const additionalParams: Record<string, string> = {};\n if (_isIOS()) {\n // iOS app identifier\n additionalParams['ibi'] = BuildInfo.packageName;\n } else if (_isAndroid()) {\n // Android app identifier\n additionalParams['apn'] = BuildInfo.packageName;\n } else {\n _fail(auth, AuthErrorCode.OPERATION_NOT_SUPPORTED);\n }\n\n // Add the display name if available\n if (BuildInfo.displayName) {\n additionalParams['appDisplayName'] = BuildInfo.displayName;\n }\n\n // Attached the hashed session ID\n additionalParams['sessionId'] = sessionDigest;\n return _getRedirectUrl(\n auth,\n provider,\n event.type,\n undefined,\n event.eventId ?? undefined,\n additionalParams\n );\n}\n\n/**\n * Validates that this app is valid for this project configuration\n */\nexport async function _validateOrigin(auth: AuthInternal): Promise<void> {\n const { BuildInfo } = _cordovaWindow();\n const request: GetProjectConfigRequest = {};\n if (_isIOS()) {\n request.iosBundleId = BuildInfo.packageName;\n } else if (_isAndroid()) {\n request.androidPackageName = BuildInfo.packageName;\n } else {\n _fail(auth, AuthErrorCode.OPERATION_NOT_SUPPORTED);\n }\n\n // Will fail automatically if package name is not authorized\n await _getProjectConfig(auth, request);\n}\n\nexport function _performRedirect(\n handlerUrl: string\n): Promise<InAppBrowserRef | null> {\n // Get the cordova plugins\n const { cordova } = _cordovaWindow();\n\n return new Promise(resolve => {\n cordova.plugins.browsertab.isAvailable(browserTabIsAvailable => {\n let iabRef: InAppBrowserRef | null = null;\n if (browserTabIsAvailable) {\n cordova.plugins.browsertab.openUrl(handlerUrl);\n } else {\n // TODO: Return the inappbrowser ref that's returned from the open call\n iabRef = cordova.InAppBrowser.open(\n handlerUrl,\n _isIOS7Or8() ? '_blank' : '_system',\n 'location=yes'\n );\n }\n resolve(iabRef);\n });\n });\n}\n\n// Thin interface wrapper to avoid circular dependency with ./events module\ninterface PassiveAuthEventListener {\n addPassiveListener(cb: () => void): void;\n removePassiveListener(cb: () => void): void;\n}\n\n/**\n * This function waits for app activity to be seen before resolving. It does\n * this by attaching listeners to various dom events. Once the app is determined\n * to be visible, this promise resolves. AFTER that resolution, the listeners\n * are detached and any browser tabs left open will be closed.\n */\nexport async function _waitForAppResume(\n auth: AuthInternal,\n eventListener: PassiveAuthEventListener,\n iabRef: InAppBrowserRef | null\n): Promise<void> {\n // Get the cordova plugins\n const { cordova } = _cordovaWindow();\n\n let cleanup = (): void => {};\n try {\n await new Promise<void>((resolve, reject) => {\n let onCloseTimer: number | null = null;\n\n // DEFINE ALL THE CALLBACKS =====\n function authEventSeen(): void {\n // Auth event was detected. Resolve this promise and close the extra\n // window if it's still open.\n resolve();\n const closeBrowserTab = cordova.plugins.browsertab?.close;\n if (typeof closeBrowserTab === 'function') {\n closeBrowserTab();\n }\n // Close inappbrowser emebedded webview in iOS7 and 8 case if still\n // open.\n if (typeof iabRef?.close === 'function') {\n iabRef.close();\n }\n }\n\n function resumed(): void {\n if (onCloseTimer) {\n // This code already ran; do not rerun.\n return;\n }\n\n onCloseTimer = window.setTimeout(() => {\n // Wait two seeconds after resume then reject.\n reject(_createError(auth, AuthErrorCode.REDIRECT_CANCELLED_BY_USER));\n }, REDIRECT_TIMEOUT_MS);\n }\n\n function visibilityChanged(): void {\n if (document?.visibilityState === 'visible') {\n resumed();\n }\n }\n\n // ATTACH ALL THE LISTENERS =====\n // Listen for the auth event\n eventListener.addPassiveListener(authEventSeen);\n\n // Listen for resume and visibility events\n document.addEventListener('resume', resumed, false);\n if (_isAndroid()) {\n document.addEventListener('visibilitychange', visibilityChanged, false);\n }\n\n // SETUP THE CLEANUP FUNCTION =====\n cleanup = () => {\n eventListener.removePassiveListener(authEventSeen);\n document.removeEventListener('resume', resumed, false);\n document.removeEventListener(\n 'visibilitychange',\n visibilityChanged,\n false\n );\n if (onCloseTimer) {\n window.clearTimeout(onCloseTimer);\n }\n };\n });\n } finally {\n cleanup();\n }\n}\n\n/**\n * Checks the configuration of the Cordova environment. This has no side effect\n * if the configuration is correct; otherwise it throws an error with the\n * missing plugin.\n */\nexport function _checkCordovaConfiguration(auth: AuthInternal): void {\n const win = _cordovaWindow();\n // Check all dependencies installed.\n // https://github.com/nordnet/cordova-universal-links-plugin\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 _assert(\n typeof win?.universalLinks?.subscribe === 'function',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-universal-links-plugin-fix'\n }\n );\n\n // https://www.npmjs.com/package/cordova-plugin-buildinfo\n _assert(\n typeof win?.BuildInfo?.packageName !== 'undefined',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-plugin-buildInfo'\n }\n );\n\n // https://github.com/google/cordova-plugin-browsertab\n _assert(\n typeof win?.cordova?.plugins?.browsertab?.openUrl === 'function',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-plugin-browsertab'\n }\n );\n _assert(\n typeof win?.cordova?.plugins?.browsertab?.isAvailable === 'function',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-plugin-browsertab'\n }\n );\n\n // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/\n _assert(\n typeof win?.cordova?.InAppBrowser?.open === 'function',\n auth,\n AuthErrorCode.INVALID_CORDOVA_CONFIGURATION,\n {\n missingPlugin: 'cordova-plugin-inappbrowser'\n }\n );\n}\n\n/**\n * Computes the SHA-256 of a session ID. The SubtleCrypto interface is only\n * available in \"secure\" contexts, which covers Cordova (which is served on a file\n * protocol).\n */\nasync function computeSha256(sessionId: string): Promise<string> {\n const bytes = stringToArrayBuffer(sessionId);\n\n // TODO: For IE11 crypto has a different name and this operation comes back\n // as an object, not a promise. This is the old proposed standard that\n // is used by IE11:\n // https://www.w3.org/TR/2013/WD-WebCryptoAPI-20130108/#cryptooperation-interface\n const buf = await crypto.subtle.digest('SHA-256', bytes);\n const arr = Array.from(new Uint8Array(buf));\n return arr.map(num => num.toString(16).padStart(2, '0')).join('');\n}\n\nfunction stringToArrayBuffer(str: string): Uint8Array {\n // This function is only meant to deal with an ASCII charset and makes\n // certain simplifying assumptions.\n debugAssert(\n /[0-9a-zA-Z]+/.test(str),\n 'Can only convert alpha-numeric strings'\n );\n if (typeof TextEncoder !== 'undefined') {\n return new TextEncoder().encode(str);\n }\n\n const buff = new ArrayBuffer(str.length);\n const view = new Uint8Array(buff);\n for (let i = 0; i < str.length; i++) {\n view[i] = str.charCodeAt(i);\n }\n return view;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystringDecode } from '@firebase/util';\nimport { AuthEventManager } from '../../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../../core/errors';\nimport { PersistedBlob, PersistenceInternal } from '../../core/persistence';\nimport {\n KeyName,\n _persistenceKeyName\n} from '../../core/persistence/persistence_user_manager';\nimport { _createError } from '../../core/util/assert';\nimport { _getInstance } from '../../core/util/instantiator';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthEvent, AuthEventType } from '../../model/popup_redirect';\nimport { browserLocalPersistence } from '../../platform_browser/persistence/local_storage';\n\nconst SESSION_ID_LENGTH = 20;\n\n/** Custom AuthEventManager that adds passive listeners to events */\nexport class CordovaAuthEventManager extends AuthEventManager {\n private readonly passiveListeners = new Set<(e: AuthEvent) => void>();\n private resolveInialized!: () => void;\n private initPromise = new Promise<void>(resolve => {\n this.resolveInialized = resolve;\n });\n\n addPassiveListener(cb: (e: AuthEvent) => void): void {\n this.passiveListeners.add(cb);\n }\n\n removePassiveListener(cb: (e: AuthEvent) => void): void {\n this.passiveListeners.delete(cb);\n }\n\n // In a Cordova environment, this manager can live through multiple redirect\n // operations\n resetRedirect(): void {\n this.queuedRedirectEvent = null;\n this.hasHandledPotentialRedirect = false;\n }\n\n /** Override the onEvent method */\n onEvent(event: AuthEvent): boolean {\n this.resolveInialized();\n this.passiveListeners.forEach(cb => cb(event));\n return super.onEvent(event);\n }\n\n async initialized(): Promise<void> {\n await this.initPromise;\n }\n}\n\n/**\n * Generates a (partial) {@link AuthEvent}.\n */\nexport function _generateNewEvent(\n auth: AuthInternal,\n type: AuthEventType,\n eventId: string | null = null\n): AuthEvent {\n return {\n type,\n eventId,\n urlResponse: null,\n sessionId: generateSessionId(),\n postBody: null,\n tenantId: auth.tenantId,\n error: _createError(auth, AuthErrorCode.NO_AUTH_EVENT)\n };\n}\n\nexport function _savePartialEvent(\n auth: AuthInternal,\n event: AuthEvent\n): Promise<void> {\n return storage()._set(persistenceKey(auth), event as object as PersistedBlob);\n}\n\nexport async function _getAndRemoveEvent(\n auth: AuthInternal\n): Promise<AuthEvent | null> {\n const event = (await storage()._get(\n persistenceKey(auth)\n )) as AuthEvent | null;\n if (event) {\n await storage()._remove(persistenceKey(auth));\n }\n return event;\n}\n\nexport function _eventFromPartialAndUrl(\n partialEvent: AuthEvent,\n url: string\n): AuthEvent | null {\n // Parse the deep link within the dynamic link URL.\n const callbackUrl = _getDeepLinkFromCallback(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.includes('/__/auth/callback')) {\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 const params = searchParamsOrEmpty(callbackUrl);\n // Get the error object corresponding to the stringified error if found.\n const errorObject = params['firebaseError']\n ? parseJsonOrNull(decodeURIComponent(params['firebaseError']))\n : null;\n const code = errorObject?.['code']?.split('auth/')?.[1];\n const error = code ? _createError(code) : null;\n if (error) {\n return {\n type: partialEvent.type,\n eventId: partialEvent.eventId,\n tenantId: partialEvent.tenantId,\n error,\n urlResponse: null,\n sessionId: null,\n postBody: null\n };\n } else {\n return {\n type: partialEvent.type,\n eventId: partialEvent.eventId,\n tenantId: partialEvent.tenantId,\n sessionId: partialEvent.sessionId,\n urlResponse: callbackUrl,\n postBody: null\n };\n }\n }\n\n return null;\n}\n\nfunction generateSessionId(): string {\n const chars = [];\n const allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < SESSION_ID_LENGTH; i++) {\n const idx = Math.floor(Math.random() * allowedChars.length);\n chars.push(allowedChars.charAt(idx));\n }\n return chars.join('');\n}\n\nfunction storage(): PersistenceInternal {\n return _getInstance(browserLocalPersistence);\n}\n\nfunction persistenceKey(auth: AuthInternal): string {\n return _persistenceKeyName(KeyName.AUTH_EVENT, auth.config.apiKey, auth.name);\n}\n\nfunction parseJsonOrNull(json: string): ReturnType<typeof JSON.parse> | null {\n try {\n return JSON.parse(json);\n } catch (e) {\n return null;\n }\n}\n\n// Exported for testing\nexport function _getDeepLinkFromCallback(url: string): string {\n const params = searchParamsOrEmpty(url);\n const link = params['link'] ? decodeURIComponent(params['link']) : undefined;\n // Double link case (automatic redirect)\n const doubleDeepLink = searchParamsOrEmpty(link)['link'];\n // iOS custom scheme links.\n const iOSDeepLink = params['deep_link_id']\n ? decodeURIComponent(params['deep_link_id'])\n : undefined;\n const iOSDoubleDeepLink = searchParamsOrEmpty(iOSDeepLink)['link'];\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * Optimistically tries to get search params from a string, or else returns an\n * empty search params object.\n */\nfunction searchParamsOrEmpty(url: string | undefined): Record<string, string> {\n if (!url?.includes('?')) {\n return {};\n }\n\n const [_, ...rest] = url.split('?');\n return querystringDecode(rest.join('?')) as Record<string, string>;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, PopupRedirectResolver } from '../../model/public_types';\nimport { browserSessionPersistence } from '../../platform_browser/persistence/session_storage';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { AuthPopup } from '../../platform_browser/util/popup';\nimport { _createError, _fail } from '../../core/util/assert';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _checkCordovaConfiguration,\n _generateHandlerUrl,\n _performRedirect,\n _validateOrigin,\n _waitForAppResume\n} from './utils';\nimport {\n CordovaAuthEventManager,\n _eventFromPartialAndUrl,\n _generateNewEvent,\n _getAndRemoveEvent,\n _savePartialEvent\n} from './events';\nimport { AuthEventManager } from '../../core/auth/auth_event_manager';\nimport { _getRedirectResult } from '../../platform_browser/strategies/redirect';\nimport {\n _clearRedirectOutcomes,\n _overrideRedirectResult\n} from '../../core/strategies/redirect';\nimport { _cordovaWindow } from '../plugins';\n\n/**\n * How long to wait for the initial auth event before concluding no\n * redirect pending\n */\nconst INITIAL_EVENT_TIMEOUT_MS = 500;\n\nclass CordovaPopupRedirectResolver implements PopupRedirectResolverInternal {\n readonly _redirectPersistence = browserSessionPersistence;\n readonly _shouldInitProactively = true; // This is lightweight for Cordova\n private readonly eventManagers = new Map<string, CordovaAuthEventManager>();\n private readonly originValidationPromises: Record<string, Promise<void>> = {};\n\n _completeRedirectFn = _getRedirectResult;\n _overrideRedirectResult = _overrideRedirectResult;\n\n async _initialize(auth: AuthInternal): Promise<CordovaAuthEventManager> {\n const key = auth._key();\n let manager = this.eventManagers.get(key);\n if (!manager) {\n manager = new CordovaAuthEventManager(auth);\n this.eventManagers.set(key, manager);\n this.attachCallbackListeners(auth, manager);\n }\n return manager;\n }\n\n _openPopup(auth: AuthInternal): Promise<AuthPopup> {\n _fail(auth, AuthErrorCode.OPERATION_NOT_SUPPORTED);\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise<void> {\n _checkCordovaConfiguration(auth);\n const manager = await this._initialize(auth);\n await manager.initialized();\n\n // Reset the persisted redirect states. This does not matter on Web where\n // the redirect always blows away application state entirely. On Cordova,\n // the app maintains control flow through the redirect.\n manager.resetRedirect();\n _clearRedirectOutcomes();\n\n await this._originValidation(auth);\n\n const event = _generateNewEvent(auth, authType, eventId);\n await _savePartialEvent(auth, event);\n const url = await _generateHandlerUrl(auth, event, provider);\n const iabRef = await _performRedirect(url);\n return _waitForAppResume(auth, manager, iabRef);\n }\n\n _isIframeWebStorageSupported(\n _auth: AuthInternal,\n _cb: (support: boolean) => unknown\n ): void {\n throw new Error('Method not implemented.');\n }\n\n _originValidation(auth: AuthInternal): Promise<void> {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n private attachCallbackListeners(\n auth: AuthInternal,\n manager: AuthEventManager\n ): void {\n // Get the global plugins\n const { universalLinks, handleOpenURL, BuildInfo } = _cordovaWindow();\n\n const noEventTimeout = setTimeout(async () => {\n // We didn't see that initial event. Clear any pending object and\n // dispatch no event\n await _getAndRemoveEvent(auth);\n manager.onEvent(generateNoEvent());\n }, INITIAL_EVENT_TIMEOUT_MS);\n\n const universalLinksCb = async (\n eventData: Record<string, string> | null\n ): Promise<void> => {\n // We have an event so we can clear the no event timeout\n clearTimeout(noEventTimeout);\n\n const partialEvent = await _getAndRemoveEvent(auth);\n let finalEvent: AuthEvent | null = null;\n if (partialEvent && eventData?.['url']) {\n finalEvent = _eventFromPartialAndUrl(partialEvent, eventData['url']);\n }\n\n // If finalEvent is never filled, trigger with no event\n manager.onEvent(finalEvent || generateNoEvent());\n };\n\n // Universal links subscriber doesn't exist for iOS, so we need to check\n if (\n typeof universalLinks !== 'undefined' &&\n typeof universalLinks.subscribe === 'function'\n ) {\n universalLinks.subscribe(null, universalLinksCb);\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 const existingHandleOpenURL = handleOpenURL;\n const packagePrefix = `${BuildInfo.packageName.toLowerCase()}://`;\n _cordovaWindow().handleOpenURL = async url => {\n if (url.toLowerCase().startsWith(packagePrefix)) {\n // We want this intentionally to float\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n universalLinksCb({ url });\n }\n // Call the developer's handler if it is present.\n if (typeof existingHandleOpenURL === 'function') {\n try {\n existingHandleOpenURL(url);\n } catch (e) {\n // This is a developer error. Don't stop the flow of the SDK.\n console.error(e);\n }\n }\n };\n }\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for Cordova\n * based applications.\n *\n * @public\n */\nexport const cordovaPopupRedirectResolver: PopupRedirectResolver =\n CordovaPopupRedirectResolver;\n\nfunction generateNoEvent(): AuthEvent {\n return {\n type: AuthEventType.UNKNOWN,\n eventId: null,\n sessionId: null,\n urlResponse: null,\n postBody: null,\n tenantId: null,\n error: _createError(AuthErrorCode.NO_AUTH_EVENT)\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable camelcase */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport * as impl from '@firebase/auth/internal';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\nimport { FirebaseError } from '@firebase/util';\n\nimport * as types from '@firebase/auth-types';\nimport { name, version } from './package.json';\nimport { Auth } from './src/auth';\nimport { PhoneAuthProvider as CompatAuthProvider } from './src/phone_auth_provider';\nimport { RecaptchaVerifier as CompatRecaptchaVerifier } from './src/recaptcha_verifier';\n\nconst AUTH_TYPE = 'auth-compat';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'auth-compat': types.FirebaseAuth;\n }\n}\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n auth: {\n (app?: FirebaseApp): types.FirebaseAuth;\n Auth: typeof types.FirebaseAuth;\n EmailAuthProvider: typeof types.EmailAuthProvider;\n EmailAuthProvider_Instance: typeof types.EmailAuthProvider_Instance;\n FacebookAuthProvider: typeof types.FacebookAuthProvider;\n FacebookAuthProvider_Instance: typeof types.FacebookAuthProvider_Instance;\n GithubAuthProvider: typeof types.GithubAuthProvider;\n GithubAuthProvider_Instance: typeof types.GithubAuthProvider_Instance;\n GoogleAuthProvider: typeof types.GoogleAuthProvider;\n GoogleAuthProvider_Instance: typeof types.GoogleAuthProvider_Instance;\n OAuthProvider: typeof types.OAuthProvider;\n SAMLAuthProvider: typeof types.SAMLAuthProvider;\n PhoneAuthProvider: typeof types.PhoneAuthProvider;\n PhoneAuthProvider_Instance: typeof types.PhoneAuthProvider_Instance;\n PhoneMultiFactorGenerator: typeof types.PhoneMultiFactorGenerator;\n RecaptchaVerifier: typeof types.RecaptchaVerifier;\n RecaptchaVerifier_Instance: typeof types.RecaptchaVerifier_Instance;\n TwitterAuthProvider: typeof types.TwitterAuthProvider;\n TwitterAuthProvider_Instance: typeof types.TwitterAuthProvider_Instance;\n };\n }\n interface FirebaseApp {\n auth?(): types.FirebaseAuth;\n }\n}\n\n// Create auth components to register with firebase.\n// Provides Auth public APIs.\nfunction registerAuthCompat(instance: _FirebaseNamespace): void {\n instance.INTERNAL.registerComponent(\n new Component(\n AUTH_TYPE,\n container => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app-compat').getImmediate();\n const authProvider = container.getProvider('auth');\n return new Auth(app, authProvider);\n },\n ComponentType.PUBLIC\n )\n .setServiceProps({\n ActionCodeInfo: {\n Operation: {\n EMAIL_SIGNIN: impl.ActionCodeOperation.EMAIL_SIGNIN,\n PASSWORD_RESET: impl.ActionCodeOperation.PASSWORD_RESET,\n RECOVER_EMAIL: impl.ActionCodeOperation.RECOVER_EMAIL,\n REVERT_SECOND_FACTOR_ADDITION:\n impl.ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION,\n VERIFY_AND_CHANGE_EMAIL:\n impl.ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n VERIFY_EMAIL: impl.ActionCodeOperation.VERIFY_EMAIL\n }\n },\n EmailAuthProvider: impl.EmailAuthProvider,\n FacebookAuthProvider: impl.FacebookAuthProvider,\n GithubAuthProvider: impl.GithubAuthProvider,\n GoogleAuthProvider: impl.GoogleAuthProvider,\n OAuthProvider: impl.OAuthProvider,\n SAMLAuthProvider: impl.SAMLAuthProvider,\n PhoneAuthProvider: CompatAuthProvider,\n PhoneMultiFactorGenerator: impl.PhoneMultiFactorGenerator,\n RecaptchaVerifier: CompatRecaptchaVerifier,\n TwitterAuthProvider: impl.TwitterAuthProvider,\n Auth,\n AuthCredential: impl.AuthCredential,\n Error: FirebaseError\n })\n .setInstantiationMode(InstantiationMode.LAZY)\n .setMultipleInstances(false)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterAuthCompat(firebase as _FirebaseNamespace);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as impl from '@firebase/auth/internal';\nimport {\n getUA,\n isBrowserExtension,\n isReactNative,\n isNode,\n isIE,\n isIndexedDBAvailable\n} from '@firebase/util';\n\ndeclare global {\n interface Document {\n documentMode?: number;\n }\n}\n\nconst CORDOVA_ONDEVICEREADY_TIMEOUT_MS = 1000;\n\nfunction _getCurrentScheme(): string | null {\n return self?.location?.protocol || null;\n}\n\n/**\n * @return {boolean} Whether the current environment is http or https.\n */\nfunction _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\n/**\n * @param {?string=} ua The user agent.\n * @return {boolean} Whether the app is rendered in a mobile iOS or Android\n * Cordova environment.\n */\nexport function _isAndroidOrIosCordovaScheme(ua: string = getUA()): boolean {\n return !!(\n (_getCurrentScheme() === 'file:' ||\n _getCurrentScheme() === 'ionic:' ||\n _getCurrentScheme() === 'capacitor:') &&\n ua.toLowerCase().match(/iphone|ipad|ipod|android/)\n );\n}\n\n/**\n * @return {boolean} Whether the environment is a native environment, where\n * CORS checks do not apply.\n */\nfunction _isNativeEnvironment(): boolean {\n return isReactNative() || isNode();\n}\n\n/**\n * Checks whether the user agent is IE11.\n * @return {boolean} True if it is IE11.\n */\nfunction _isIe11(): boolean {\n return isIE() && document?.documentMode === 11;\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 */\nfunction _isEdge(ua: string = getUA()): boolean {\n return /Edge\\/\\d+/.test(ua);\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 */\nfunction _isLocalStorageNotSynchronized(ua: string = getUA()): boolean {\n return _isIe11() || _isEdge(ua);\n}\n\n/** @return {boolean} Whether web storage is supported. */\nexport function _isWebStorageSupported(): boolean {\n try {\n const storage = self.localStorage;\n const key = impl._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 (_isLocalStorageNotSynchronized()) {\n // In such browsers, if indexedDB is not supported, an iframe cannot be\n // notified of the popup sign in result.\n return isIndexedDBAvailable();\n }\n return true;\n }\n } catch (e) {\n // localStorage is not available from a worker. Test availability of\n // indexedDB.\n return _isWorker() && isIndexedDBAvailable();\n }\n return false;\n}\n\n/**\n * @param {?Object=} global The optional global scope.\n * @return {boolean} Whether current environment is a worker.\n */\nexport function _isWorker(): boolean {\n // WorkerGlobalScope only defined in worker environment.\n return (\n typeof global !== 'undefined' &&\n 'WorkerGlobalScope' in global &&\n 'importScripts' in global\n );\n}\n\nexport function _isPopupRedirectSupported(): boolean {\n return (\n (_isHttpOrHttps() ||\n isBrowserExtension() ||\n _isAndroidOrIosCordovaScheme()) &&\n // React Native with remote debugging reports its location.protocol as\n // http.\n !_isNativeEnvironment() &&\n // Local storage has to be supported for browser popup and redirect\n // operations to work.\n _isWebStorageSupported() &&\n // DOM, popups and redirects are not supported within a worker.\n !_isWorker()\n );\n}\n\n/** Quick check that indicates the platform *may* be Cordova */\nexport function _isLikelyCordova(): boolean {\n return _isAndroidOrIosCordovaScheme() && typeof document !== 'undefined';\n}\n\nexport async function _isCordova(): Promise<boolean> {\n if (!_isLikelyCordova()) {\n return false;\n }\n\n return new Promise(resolve => {\n const timeoutId = setTimeout(() => {\n // We've waited long enough; the telltale Cordova event didn't happen\n resolve(false);\n }, CORDOVA_ONDEVICEREADY_TIMEOUT_MS);\n\n document.addEventListener('deviceready', () => {\n clearTimeout(timeoutId);\n resolve(true);\n });\n });\n}\n\nexport function _getSelfWindow(): Window | null {\n return typeof window !== 'undefined' ? window : null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport { isIndexedDBAvailable, isNode, isReactNative } from '@firebase/util';\nimport { _getSelfWindow, _isWebStorageSupported, _isWorker } from './platform';\n\nexport const Persistence = {\n LOCAL: 'local',\n NONE: 'none',\n SESSION: 'session'\n};\n\nconst _assert: typeof exp._assert = exp._assert;\n\nconst PERSISTENCE_KEY = 'persistence';\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 */\nexport function _validatePersistenceArgument(\n auth: exp.Auth,\n persistence: string\n): void {\n _assert(\n Object.values(Persistence).includes(persistence),\n auth,\n exp.AuthErrorCode.INVALID_PERSISTENCE\n );\n // Validate if the specified type is supported in the current environment.\n if (isReactNative()) {\n // This is only supported in a browser.\n _assert(\n persistence !== Persistence.SESSION,\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n if (isNode()) {\n // Only none is supported in Node.js.\n _assert(\n persistence === Persistence.NONE,\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n if (_isWorker()) {\n // In a worker environment, either LOCAL or NONE are supported.\n // If indexedDB not supported and LOCAL provided, throw an error\n _assert(\n persistence === Persistence.NONE ||\n (persistence === Persistence.LOCAL && isIndexedDBAvailable()),\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n return;\n }\n // This is restricted by what the browser supports.\n _assert(\n persistence === Persistence.NONE || _isWebStorageSupported(),\n auth,\n exp.AuthErrorCode.UNSUPPORTED_PERSISTENCE\n );\n}\n\nexport async function _savePersistenceForRedirect(\n auth: exp.AuthInternal\n): Promise<void> {\n await auth._initializationPromise;\n const session = getSessionStorageIfAvailable();\n const key = exp._persistenceKeyName(\n PERSISTENCE_KEY,\n auth.config.apiKey,\n auth.name\n );\n if (session) {\n session.setItem(key, auth._getPersistence());\n }\n}\n\nexport function _getPersistencesFromRedirect(\n apiKey: string,\n appName: string\n): exp.Persistence[] {\n const session = getSessionStorageIfAvailable();\n if (!session) {\n return [];\n }\n\n const key = exp._persistenceKeyName(PERSISTENCE_KEY, apiKey, appName);\n const persistence = session.getItem(key);\n\n switch (persistence) {\n case Persistence.NONE:\n return [exp.inMemoryPersistence];\n case Persistence.LOCAL:\n return [exp.indexedDBLocalPersistence, exp.browserSessionPersistence];\n case Persistence.SESSION:\n return [exp.browserSessionPersistence];\n default:\n return [];\n }\n}\n\n/** Returns session storage, or null if the property access errors */\nfunction getSessionStorageIfAvailable(): Storage | null {\n try {\n return _getSelfWindow()?.sessionStorage || null;\n } catch (e) {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport { _isCordova, _isLikelyCordova } from './platform';\n\nconst _assert: typeof exp._assert = exp._assert;\n\n/** Platform-agnostic popup-redirect resolver */\nexport class CompatPopupRedirectResolver\n implements exp.PopupRedirectResolverInternal\n{\n // Create both resolvers for dynamic resolution later\n private readonly browserResolver: exp.PopupRedirectResolverInternal =\n exp._getInstance(exp.browserPopupRedirectResolver);\n private readonly cordovaResolver: exp.PopupRedirectResolverInternal =\n exp._getInstance(exp.cordovaPopupRedirectResolver);\n // The actual resolver in use: either browserResolver or cordovaResolver.\n private underlyingResolver: exp.PopupRedirectResolverInternal | null = null;\n _redirectPersistence = exp.browserSessionPersistence;\n\n _completeRedirectFn: (\n auth: exp.Auth,\n resolver: exp.PopupRedirectResolver,\n bypassAuthState: boolean\n ) => Promise<exp.UserCredential | null> = exp._getRedirectResult;\n _overrideRedirectResult = exp._overrideRedirectResult;\n\n async _initialize(auth: exp.AuthImpl): Promise<exp.EventManager> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._initialize(auth);\n }\n\n async _openPopup(\n auth: exp.AuthImpl,\n provider: exp.AuthProvider,\n authType: exp.AuthEventType,\n eventId?: string\n ): Promise<exp.AuthPopup> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._openPopup(\n auth,\n provider,\n authType,\n eventId\n );\n }\n\n async _openRedirect(\n auth: exp.AuthImpl,\n provider: exp.AuthProvider,\n authType: exp.AuthEventType,\n eventId?: string\n ): Promise<void> {\n await this.selectUnderlyingResolver();\n return this.assertedUnderlyingResolver._openRedirect(\n auth,\n provider,\n authType,\n eventId\n );\n }\n\n _isIframeWebStorageSupported(\n auth: exp.AuthImpl,\n cb: (support: boolean) => unknown\n ): void {\n this.assertedUnderlyingResolver._isIframeWebStorageSupported(auth, cb);\n }\n\n _originValidation(auth: exp.Auth): Promise<void> {\n return this.assertedUnderlyingResolver._originValidation(auth);\n }\n\n get _shouldInitProactively(): boolean {\n return _isLikelyCordova() || this.browserResolver._shouldInitProactively;\n }\n\n private get assertedUnderlyingResolver(): exp.PopupRedirectResolverInternal {\n _assert(this.underlyingResolver, exp.AuthErrorCode.INTERNAL_ERROR);\n return this.underlyingResolver;\n }\n\n private async selectUnderlyingResolver(): Promise<void> {\n if (this.underlyingResolver) {\n return;\n }\n\n // We haven't yet determined whether or not we're in Cordova; go ahead\n // and determine that state now.\n const isCordova = await _isCordova();\n this.underlyingResolver = isCordova\n ? this.cordovaResolver\n : this.browserResolver;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Forward direction wrapper from Compat --unwrap-> Exp */\nexport interface Wrapper<T> {\n unwrap(): T;\n}\n\n/** Reverse direction wrapper from Exp --wrapped--> Compat */\nexport interface ReverseWrapper<T> {\n wrapped(): T;\n}\n\nexport function unwrap<T>(object: unknown): T {\n return (object as Wrapper<T>).unwrap();\n}\n\nexport function wrapped<T>(object: unknown): T {\n return (object as ReverseWrapper<T>).wrapped();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { FirebaseError } from '@firebase/util';\nimport { Auth } from './auth';\nimport { User } from './user';\nimport { unwrap, wrapped } from './wrap';\n\nfunction credentialFromResponse(\n userCredential: exp.UserCredentialInternal\n): exp.AuthCredential | null {\n return credentialFromObject(userCredential);\n}\n\nfunction attachExtraErrorFields(auth: exp.Auth, e: FirebaseError): void {\n // The response contains all fields from the server which may or may not\n // actually match the underlying type\n const response = (e.customData as exp.TaggedWithTokenResponse | undefined)\n ?._tokenResponse as unknown as Record<string, string>;\n if ((e as FirebaseError)?.code === 'auth/multi-factor-auth-required') {\n const mfaErr = e as compat.MultiFactorError;\n mfaErr.resolver = new MultiFactorResolver(\n auth,\n exp.getMultiFactorResolver(auth, e as exp.MultiFactorError)\n );\n } else if (response) {\n const credential = credentialFromObject(e);\n const credErr = e as compat.AuthError;\n if (credential) {\n credErr.credential = credential;\n credErr.tenantId = response.tenantId || undefined;\n credErr.email = response.email || undefined;\n credErr.phoneNumber = response.phoneNumber || undefined;\n }\n }\n}\n\nfunction credentialFromObject(\n object: FirebaseError | exp.UserCredential\n): exp.AuthCredential | null {\n const { _tokenResponse } = (\n object instanceof FirebaseError ? object.customData : object\n ) as exp.TaggedWithTokenResponse;\n if (!_tokenResponse) {\n return null;\n }\n\n // Handle phone Auth credential responses, as they have a different format\n // from other backend responses (i.e. no providerId). This is also only the\n // case for user credentials (does not work for errors).\n if (!(object instanceof FirebaseError)) {\n if ('temporaryProof' in _tokenResponse && 'phoneNumber' in _tokenResponse) {\n return exp.PhoneAuthProvider.credentialFromResult(object);\n }\n }\n\n const providerId = _tokenResponse.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 === exp.ProviderId.PASSWORD) {\n return null;\n }\n\n let provider: Pick<\n typeof exp.OAuthProvider,\n 'credentialFromResult' | 'credentialFromError'\n >;\n switch (providerId) {\n case exp.ProviderId.GOOGLE:\n provider = exp.GoogleAuthProvider;\n break;\n case exp.ProviderId.FACEBOOK:\n provider = exp.FacebookAuthProvider;\n break;\n case exp.ProviderId.GITHUB:\n provider = exp.GithubAuthProvider;\n break;\n case exp.ProviderId.TWITTER:\n provider = exp.TwitterAuthProvider;\n break;\n default:\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce\n } = _tokenResponse as exp.SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n // TODO(avolkovi): uncomment this and get it working with SAML & OIDC\n if (pendingToken) {\n if (providerId.startsWith('saml.')) {\n return exp.SAMLAuthCredential._create(providerId, pendingToken);\n } else {\n // OIDC and non-default providers excluding Twitter.\n return exp.OAuthCredential._fromParams({\n providerId,\n signInMethod: providerId,\n pendingToken,\n idToken: oauthIdToken,\n accessToken: oauthAccessToken\n });\n }\n }\n return new exp.OAuthProvider(providerId).credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n rawNonce: nonce\n });\n }\n\n return object instanceof FirebaseError\n ? provider.credentialFromError(object)\n : provider.credentialFromResult(object);\n}\n\nexport function convertCredential(\n auth: exp.Auth,\n credentialPromise: Promise<exp.UserCredential>\n): Promise<compat.UserCredential> {\n return credentialPromise\n .catch(e => {\n if (e instanceof FirebaseError) {\n attachExtraErrorFields(auth, e);\n }\n throw e;\n })\n .then(credential => {\n const operationType = credential.operationType;\n const user = credential.user;\n\n return {\n operationType,\n credential: credentialFromResponse(\n credential as exp.UserCredentialInternal\n ),\n additionalUserInfo: exp.getAdditionalUserInfo(\n credential as exp.UserCredential\n ),\n user: User.getOrCreate(user)\n };\n });\n}\n\nexport async function convertConfirmationResult(\n auth: exp.Auth,\n confirmationResultPromise: Promise<exp.ConfirmationResult>\n): Promise<compat.ConfirmationResult> {\n const confirmationResultExp = await confirmationResultPromise;\n return {\n verificationId: confirmationResultExp.verificationId,\n confirm: (verificationCode: string) =>\n convertCredential(auth, confirmationResultExp.confirm(verificationCode))\n };\n}\n\nclass MultiFactorResolver implements compat.MultiFactorResolver {\n readonly auth: Auth;\n constructor(\n auth: exp.Auth,\n private readonly resolver: exp.MultiFactorResolver\n ) {\n this.auth = wrapped(auth);\n }\n\n get session(): compat.MultiFactorSession {\n return this.resolver.session;\n }\n\n get hints(): compat.MultiFactorInfo[] {\n return this.resolver.hints;\n }\n\n resolveSignIn(\n assertion: compat.MultiFactorAssertion\n ): Promise<compat.UserCredential> {\n return convertCredential(\n unwrap(this.auth),\n this.resolver.resolveSignIn(assertion as exp.MultiFactorAssertion)\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Compat } from '@firebase/util';\nimport { _savePersistenceForRedirect } from './persistence';\nimport { CompatPopupRedirectResolver } from './popup_redirect';\nimport {\n convertConfirmationResult,\n convertCredential\n} from './user_credential';\n\nexport class User implements compat.User, Compat<exp.User> {\n // Maintain a map so that there's always a 1:1 mapping between new User and\n // legacy compat users\n private static readonly USER_MAP = new WeakMap<exp.User, User>();\n\n readonly multiFactor: compat.MultiFactorUser;\n\n private constructor(readonly _delegate: exp.User) {\n this.multiFactor = exp.multiFactor(_delegate);\n }\n\n static getOrCreate(user: exp.User): User {\n if (!User.USER_MAP.has(user)) {\n User.USER_MAP.set(user, new User(user));\n }\n\n return User.USER_MAP.get(user)!;\n }\n\n delete(): Promise<void> {\n return this._delegate.delete();\n }\n reload(): Promise<void> {\n return this._delegate.reload();\n }\n toJSON(): object {\n return this._delegate.toJSON();\n }\n getIdTokenResult(forceRefresh?: boolean): Promise<compat.IdTokenResult> {\n return this._delegate.getIdTokenResult(forceRefresh);\n }\n getIdToken(forceRefresh?: boolean): Promise<string> {\n return this._delegate.getIdToken(forceRefresh);\n }\n linkAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.linkWithCredential(credential);\n }\n async linkWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.linkWithCredential(this._delegate, credential as exp.AuthCredential)\n );\n }\n async linkWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this.auth,\n exp.linkWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier)\n );\n }\n async linkWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.linkWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async linkWithRedirect(provider: compat.AuthProvider): Promise<void> {\n await _savePersistenceForRedirect(exp._castAuth(this.auth));\n return exp.linkWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n reauthenticateAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.reauthenticateWithCredential(credential);\n }\n async reauthenticateWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth as unknown as exp.Auth,\n exp.reauthenticateWithCredential(\n this._delegate,\n credential as exp.AuthCredential\n )\n );\n }\n reauthenticateWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this.auth,\n exp.reauthenticateWithPhoneNumber(\n this._delegate,\n phoneNumber,\n applicationVerifier\n )\n );\n }\n reauthenticateWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this.auth,\n exp.reauthenticateWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async reauthenticateWithRedirect(\n provider: compat.AuthProvider\n ): Promise<void> {\n await _savePersistenceForRedirect(exp._castAuth(this.auth));\n return exp.reauthenticateWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n sendEmailVerification(\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.sendEmailVerification(this._delegate, actionCodeSettings);\n }\n async unlink(providerId: string): Promise<compat.User> {\n await exp.unlink(this._delegate, providerId);\n return this;\n }\n updateEmail(newEmail: string): Promise<void> {\n return exp.updateEmail(this._delegate, newEmail);\n }\n updatePassword(newPassword: string): Promise<void> {\n return exp.updatePassword(this._delegate, newPassword);\n }\n updatePhoneNumber(phoneCredential: compat.AuthCredential): Promise<void> {\n return exp.updatePhoneNumber(\n this._delegate,\n phoneCredential as exp.PhoneAuthCredential\n );\n }\n updateProfile(profile: {\n displayName?: string | null;\n photoURL?: string | null;\n }): Promise<void> {\n return exp.updateProfile(this._delegate, profile);\n }\n verifyBeforeUpdateEmail(\n newEmail: string,\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.verifyBeforeUpdateEmail(\n this._delegate,\n newEmail,\n actionCodeSettings\n );\n }\n get emailVerified(): boolean {\n return this._delegate.emailVerified;\n }\n get isAnonymous(): boolean {\n return this._delegate.isAnonymous;\n }\n get metadata(): compat.UserMetadata {\n return this._delegate.metadata;\n }\n get phoneNumber(): string | null {\n return this._delegate.phoneNumber;\n }\n get providerData(): Array<compat.UserInfo | null> {\n return this._delegate.providerData;\n }\n get refreshToken(): string {\n return this._delegate.refreshToken;\n }\n get tenantId(): string | null {\n return this._delegate.tenantId;\n }\n get displayName(): string | null {\n return this._delegate.displayName;\n }\n get email(): string | null {\n return this._delegate.email;\n }\n get photoURL(): string | null {\n return this._delegate.photoURL;\n }\n get providerId(): string {\n return this._delegate.providerId;\n }\n get uid(): string {\n return this._delegate.uid;\n }\n private get auth(): exp.Auth {\n return (this._delegate as exp.UserImpl).auth as unknown as exp.Auth;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Provider } from '@firebase/component';\nimport { ErrorFn, Observer, Unsubscribe } from '@firebase/util';\n\nimport {\n _validatePersistenceArgument,\n Persistence,\n _getPersistencesFromRedirect,\n _savePersistenceForRedirect\n} from './persistence';\nimport { _isPopupRedirectSupported } from './platform';\nimport { CompatPopupRedirectResolver } from './popup_redirect';\nimport { User } from './user';\nimport {\n convertConfirmationResult,\n convertCredential\n} from './user_credential';\nimport { ReverseWrapper, Wrapper } from './wrap';\n\nconst _assert: typeof exp._assert = exp._assert;\n\nexport class Auth\n implements compat.FirebaseAuth, Wrapper<exp.Auth>, _FirebaseService\n{\n static Persistence = Persistence;\n readonly _delegate: exp.AuthImpl;\n\n constructor(readonly app: FirebaseApp, provider: Provider<'auth'>) {\n if (provider.isInitialized()) {\n this._delegate = provider.getImmediate() as exp.AuthImpl;\n this.linkUnderlyingAuth();\n return;\n }\n\n const { apiKey } = app.options;\n // TODO: platform needs to be determined using heuristics\n _assert(apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n\n // TODO: platform needs to be determined using heuristics\n _assert(apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n\n // Only use a popup/redirect resolver in browser environments\n const resolver =\n typeof window !== 'undefined' ? CompatPopupRedirectResolver : undefined;\n this._delegate = provider.initialize({\n options: {\n persistence: buildPersistenceHierarchy(apiKey, app.name),\n popupRedirectResolver: resolver\n }\n }) as exp.AuthImpl;\n\n this._delegate._updateErrorMap(exp.debugErrorMap);\n this.linkUnderlyingAuth();\n }\n\n get emulatorConfig(): compat.EmulatorConfig | null {\n return this._delegate.emulatorConfig;\n }\n\n get currentUser(): compat.User | null {\n if (!this._delegate.currentUser) {\n return null;\n }\n\n return User.getOrCreate(this._delegate.currentUser);\n }\n get languageCode(): string | null {\n return this._delegate.languageCode;\n }\n set languageCode(languageCode: string | null) {\n this._delegate.languageCode = languageCode;\n }\n get settings(): compat.AuthSettings {\n return this._delegate.settings;\n }\n get tenantId(): string | null {\n return this._delegate.tenantId;\n }\n set tenantId(tid: string | null) {\n this._delegate.tenantId = tid;\n }\n useDeviceLanguage(): void {\n this._delegate.useDeviceLanguage();\n }\n signOut(): Promise<void> {\n return this._delegate.signOut();\n }\n useEmulator(url: string, options?: { disableWarnings: boolean }): void {\n exp.connectAuthEmulator(this._delegate, url, options);\n }\n applyActionCode(code: string): Promise<void> {\n return exp.applyActionCode(this._delegate, code);\n }\n\n checkActionCode(code: string): Promise<compat.ActionCodeInfo> {\n return exp.checkActionCode(this._delegate, code);\n }\n\n confirmPasswordReset(code: string, newPassword: string): Promise<void> {\n return exp.confirmPasswordReset(this._delegate, code, newPassword);\n }\n\n async createUserWithEmailAndPassword(\n email: string,\n password: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.createUserWithEmailAndPassword(this._delegate, email, password)\n );\n }\n fetchProvidersForEmail(email: string): Promise<string[]> {\n return this.fetchSignInMethodsForEmail(email);\n }\n fetchSignInMethodsForEmail(email: string): Promise<string[]> {\n return exp.fetchSignInMethodsForEmail(this._delegate, email);\n }\n isSignInWithEmailLink(emailLink: string): boolean {\n return exp.isSignInWithEmailLink(this._delegate, emailLink);\n }\n async getRedirectResult(): Promise<compat.UserCredential> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const credential = await exp.getRedirectResult(\n this._delegate,\n CompatPopupRedirectResolver\n );\n if (!credential) {\n return {\n credential: null,\n user: null\n };\n }\n return convertCredential(this._delegate, Promise.resolve(credential));\n }\n\n // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.\n // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it\n // out of autogenerated documentation pages to reduce accidental misuse.\n addFrameworkForLogging(framework: string): void {\n exp.addFrameworkForLogging(this._delegate, framework);\n }\n\n onAuthStateChanged(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n errorFn?: (error: compat.Error) => unknown,\n completed?: Unsubscribe\n ): Unsubscribe {\n const { next, error, complete } = wrapObservers(\n nextOrObserver,\n errorFn,\n completed\n );\n return this._delegate.onAuthStateChanged(next!, error, complete);\n }\n onIdTokenChanged(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n errorFn?: (error: compat.Error) => unknown,\n completed?: Unsubscribe\n ): Unsubscribe {\n const { next, error, complete } = wrapObservers(\n nextOrObserver,\n errorFn,\n completed\n );\n return this._delegate.onIdTokenChanged(next!, error, complete);\n }\n sendSignInLinkToEmail(\n email: string,\n actionCodeSettings: compat.ActionCodeSettings\n ): Promise<void> {\n return exp.sendSignInLinkToEmail(this._delegate, email, actionCodeSettings);\n }\n sendPasswordResetEmail(\n email: string,\n actionCodeSettings?: compat.ActionCodeSettings | null\n ): Promise<void> {\n return exp.sendPasswordResetEmail(\n this._delegate,\n email,\n actionCodeSettings || undefined\n );\n }\n async setPersistence(persistence: string): Promise<void> {\n _validatePersistenceArgument(this._delegate, persistence);\n let converted;\n switch (persistence) {\n case Persistence.SESSION:\n converted = exp.browserSessionPersistence;\n break;\n case Persistence.LOCAL:\n // Not using isIndexedDBAvailable() since it only checks if indexedDB is defined.\n const isIndexedDBFullySupported = await exp\n ._getInstance<exp.PersistenceInternal>(exp.indexedDBLocalPersistence)\n ._isAvailable();\n converted = isIndexedDBFullySupported\n ? exp.indexedDBLocalPersistence\n : exp.browserLocalPersistence;\n break;\n case Persistence.NONE:\n converted = exp.inMemoryPersistence;\n break;\n default:\n return exp._fail(exp.AuthErrorCode.ARGUMENT_ERROR, {\n appName: this._delegate.name\n });\n }\n\n return this._delegate.setPersistence(converted);\n }\n\n signInAndRetrieveDataWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return this.signInWithCredential(credential);\n }\n signInAnonymously(): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInAnonymously(this._delegate)\n );\n }\n signInWithCredential(\n credential: compat.AuthCredential\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithCredential(this._delegate, credential as exp.AuthCredential)\n );\n }\n signInWithCustomToken(token: string): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithCustomToken(this._delegate, token)\n );\n }\n signInWithEmailAndPassword(\n email: string,\n password: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithEmailAndPassword(this._delegate, email, password)\n );\n }\n signInWithEmailLink(\n email: string,\n emailLink?: string\n ): Promise<compat.UserCredential> {\n return convertCredential(\n this._delegate,\n exp.signInWithEmailLink(this._delegate, email, emailLink)\n );\n }\n signInWithPhoneNumber(\n phoneNumber: string,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<compat.ConfirmationResult> {\n return convertConfirmationResult(\n this._delegate,\n exp.signInWithPhoneNumber(\n this._delegate,\n phoneNumber,\n applicationVerifier\n )\n );\n }\n async signInWithPopup(\n provider: compat.AuthProvider\n ): Promise<compat.UserCredential> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n return convertCredential(\n this._delegate,\n exp.signInWithPopup(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n )\n );\n }\n async signInWithRedirect(provider: compat.AuthProvider): Promise<void> {\n _assert(\n _isPopupRedirectSupported(),\n this._delegate,\n exp.AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n\n await _savePersistenceForRedirect(this._delegate);\n return exp.signInWithRedirect(\n this._delegate,\n provider as exp.AuthProvider,\n CompatPopupRedirectResolver\n );\n }\n updateCurrentUser(user: compat.User | null): Promise<void> {\n // remove ts-ignore once overloads are defined for exp functions to accept compat objects\n // @ts-ignore\n return this._delegate.updateCurrentUser(user);\n }\n verifyPasswordResetCode(code: string): Promise<string> {\n return exp.verifyPasswordResetCode(this._delegate, code);\n }\n unwrap(): exp.Auth {\n return this._delegate;\n }\n _delete(): Promise<void> {\n return this._delegate._delete();\n }\n private linkUnderlyingAuth(): void {\n (this._delegate as unknown as ReverseWrapper<Auth>).wrapped = () => this;\n }\n}\n\nfunction wrapObservers(\n nextOrObserver: Observer<unknown> | ((a: compat.User | null) => unknown),\n error?: (error: compat.Error) => unknown,\n complete?: Unsubscribe\n): Partial<Observer<exp.User | null>> {\n let next = nextOrObserver;\n if (typeof nextOrObserver !== 'function') {\n ({ next, error, complete } = nextOrObserver);\n }\n\n // We know 'next' is now a function\n const oldNext = next as (a: compat.User | null) => unknown;\n\n const newNext = (user: exp.User | null): unknown =>\n oldNext(user && User.getOrCreate(user as exp.User));\n return {\n next: newNext,\n error: error as ErrorFn,\n complete\n };\n}\n\nfunction buildPersistenceHierarchy(\n apiKey: string,\n appName: string\n): exp.Persistence[] {\n // Note this is slightly different behavior: in this case, the stored\n // persistence is checked *first* rather than last. This is because we want\n // to prefer stored persistence type in the hierarchy. This is an empty\n // array if window is not available or there is no pending redirect\n const persistences = _getPersistencesFromRedirect(apiKey, appName);\n\n // If \"self\" is available, add indexedDB\n if (\n typeof self !== 'undefined' &&\n !persistences.includes(exp.indexedDBLocalPersistence)\n ) {\n persistences.push(exp.indexedDBLocalPersistence);\n }\n\n // If \"window\" is available, add HTML Storage persistences\n if (typeof window !== 'undefined') {\n for (const persistence of [\n exp.browserLocalPersistence,\n exp.browserSessionPersistence\n ]) {\n if (!persistences.includes(persistence)) {\n persistences.push(persistence);\n }\n }\n }\n\n // Add in-memory as a final fallback\n if (!persistences.includes(exp.inMemoryPersistence)) {\n persistences.push(exp.inMemoryPersistence);\n }\n\n return persistences;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as api from '../../api/authentication/email_and_password';\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthProvider } from '../providers/email';\nimport { _getCurrentUrl } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { getModularInstance } from '@firebase/util';\nimport { _castAuth } from '../auth/auth_impl';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\n\n/**\n * Sends a sign-in email link to the user with the specified email.\n *\n * @remarks\n * The sign-in operation has to always be completed in the app unlike other out of band email\n * actions (password reset and email verifications). This is because, at the end of the flow,\n * the user is expected to be signed in and their Auth state persisted within the app.\n *\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\n * address and the email link supplied in the email sent to the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param authInternal - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n email: string,\n actionCodeSettings: ActionCodeSettings\n): Promise<void> {\n const authInternal = _castAuth(auth);\n const request: api.EmailSignInRequest = {\n requestType: ActionCodeOperation.EMAIL_SIGNIN,\n email,\n clientType: RecaptchaClientType.WEB\n };\n function setActionCodeSettings(\n request: api.EmailSignInRequest,\n actionCodeSettings: ActionCodeSettings\n ): void {\n _assert(\n actionCodeSettings.handleCodeInApp,\n authInternal,\n AuthErrorCode.ARGUMENT_ERROR\n );\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n authInternal,\n request,\n actionCodeSettings\n );\n }\n }\n setActionCodeSettings(request, actionCodeSettings);\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n api.sendSignInLinkToEmail\n );\n}\n\n/**\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\n *\n * @param auth - The {@link Auth} instance.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport function isSignInWithEmailLink(auth: Auth, emailLink: string): boolean {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n return actionCodeUrl?.operation === ActionCodeOperation.EMAIL_SIGNIN;\n}\n\n/**\n * Asynchronously signs in using an email and sign-in email link.\n *\n * @remarks\n * If no link is passed, the link is inferred from the current URL.\n *\n * Fails with an error if the email address is invalid or OTP in email link expires.\n *\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport async function signInWithEmailLink(\n auth: Auth,\n email: string,\n emailLink?: string\n): Promise<UserCredential> {\n const authModular = getModularInstance(auth);\n const credential = EmailAuthProvider.credentialWithLink(\n email,\n emailLink || _getCurrentUrl()\n );\n // Check if the tenant ID in the email link matches the tenant ID on Auth\n // instance.\n _assert(\n credential._tenantId === (authModular.tenantId || null),\n authModular,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n return signInWithCredential(authModular, credential);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _castAuth } from '../src/core/auth/auth_impl';\nimport { Auth } from '../src/model/public_types';\n\n/**\n * This interface is intended only for use by @firebase/auth-compat, do not use directly\n */\nexport * from '../index';\n\nexport { SignInWithIdpResponse } from '../src/api/authentication/idp';\nexport { AuthErrorCode } from '../src/core/errors';\nexport { PersistenceInternal } from '../src/core/persistence';\nexport { _persistenceKeyName } from '../src/core/persistence/persistence_user_manager';\nexport { UserImpl } from '../src/core/user/user_impl';\nexport { _getInstance } from '../src/core/util/instantiator';\nexport {\n PopupRedirectResolverInternal,\n EventManager,\n AuthEventType\n} from '../src/model/popup_redirect';\nexport { UserCredentialInternal, UserParameters } from '../src/model/user';\nexport { AuthInternal, ConfigInternal } from '../src/model/auth';\nexport { DefaultConfig, AuthImpl, _castAuth } from '../src/core/auth/auth_impl';\n\nexport { ClientPlatform, _getClientVersion } from '../src/core/util/version';\n\nexport { _generateEventId } from '../src/core/util/event_id';\nexport { TaggedWithTokenResponse } from '../src/model/id_token';\nexport { _fail, _assert } from '../src/core/util/assert';\nexport { AuthPopup } from '../src/platform_browser/util/popup';\nexport { _getRedirectResult } from '../src/platform_browser/strategies/redirect';\nexport { _overrideRedirectResult } from '../src/core/strategies/redirect';\nexport { cordovaPopupRedirectResolver } from '../src/platform_cordova/popup_redirect/popup_redirect';\nexport { FetchProvider } from '../src/core/util/fetch_provider';\nexport { SAMLAuthCredential } from '../src/core/credentials/saml';\n\n// This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.\n// It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it out\n// of autogenerated documentation pages to reduce accidental misuse.\nexport function addFrameworkForLogging(auth: Auth, framework: string): void {\n _castAuth(auth)._logFramework(framework);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, UserCredential } from '../../model/public_types';\nimport { signUp } from '../../api/authentication/sign_up';\nimport { UserInternal } from '../../model/user';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Asynchronously signs in as an anonymous user.\n *\n * @remarks\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\n * new anonymous user identity will be created and returned.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport async function signInAnonymously(auth: Auth): Promise<UserCredential> {\n const authInternal = _castAuth(auth);\n await authInternal._initializationPromise;\n if (authInternal.currentUser?.isAnonymous) {\n // If an anonymous user is already signed in, no need to sign them in again.\n return new UserCredentialImpl({\n user: authInternal.currentUser as UserInternal,\n providerId: null,\n operationType: OperationType.SIGN_IN\n });\n }\n const response = await signUp(authInternal, {\n returnSecureToken: true\n });\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response,\n true\n );\n await authInternal._updateCurrentUser(userCredential.user);\n return userCredential;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport firebase from '@firebase/app-compat';\nimport { Compat } from '@firebase/util';\nimport { unwrap } from './wrap';\n\nexport class PhoneAuthProvider\n implements compat.PhoneAuthProvider, Compat<exp.PhoneAuthProvider>\n{\n providerId = 'phone';\n readonly _delegate: exp.PhoneAuthProvider;\n\n static PHONE_SIGN_IN_METHOD = exp.PhoneAuthProvider.PHONE_SIGN_IN_METHOD;\n static PROVIDER_ID = exp.PhoneAuthProvider.PROVIDER_ID;\n\n static credential(\n verificationId: string,\n verificationCode: string\n ): compat.AuthCredential {\n return exp.PhoneAuthProvider.credential(verificationId, verificationCode);\n }\n\n constructor() {\n // TODO: remove ts-ignore when moving types from auth-types to auth-compat\n // @ts-ignore\n this._delegate = new exp.PhoneAuthProvider(unwrap(firebase.auth!()));\n }\n\n verifyPhoneNumber(\n phoneInfoOptions:\n | string\n | compat.PhoneSingleFactorInfoOptions\n | compat.PhoneMultiFactorEnrollInfoOptions\n | compat.PhoneMultiFactorSignInInfoOptions,\n applicationVerifier: compat.ApplicationVerifier\n ): Promise<string> {\n return this._delegate.verifyPhoneNumber(\n // The implementation matches but the types are subtly incompatible\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n phoneInfoOptions as any,\n applicationVerifier\n );\n }\n\n unwrap(): exp.PhoneAuthProvider {\n return this._delegate;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, { FirebaseApp } from '@firebase/app-compat';\nimport * as exp from '@firebase/auth/internal';\nimport * as compat from '@firebase/auth-types';\nimport { Compat } from '@firebase/util';\n\nconst _assert: typeof exp._assert = exp._assert;\n\nexport class RecaptchaVerifier\n implements compat.RecaptchaVerifier, Compat<exp.ApplicationVerifier>\n{\n readonly _delegate: exp.RecaptchaVerifier;\n type: string;\n constructor(\n container: HTMLElement | string,\n parameters?: object | null,\n app: FirebaseApp = firebase.app()\n ) {\n // API key is required for web client RPC calls.\n _assert(app.options?.apiKey, exp.AuthErrorCode.INVALID_API_KEY, {\n appName: app.name\n });\n this._delegate = new exp.RecaptchaVerifier(\n // TODO: remove ts-ignore when moving types from auth-types to auth-compat\n // @ts-ignore\n app.auth!(),\n container,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parameters as any\n );\n this.type = this._delegate.type;\n }\n clear(): void {\n this._delegate.clear();\n }\n render(): Promise<number> {\n return this._delegate.render();\n }\n verify(): Promise<string> {\n return this._delegate.verify();\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 */\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 domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(private domStorage_: Storage) {}\n\n /**\n * @param key - The key to save the value under\n * @param 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 * @returns 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 remove(key: string) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n\n isInMemoryStorage: boolean;\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 */\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 domStorageName - Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @returns 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { doubleToIEEE754String } from '../util/util';\n\nimport { Node } from './Node';\n\nlet MAX_NODE: Node;\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\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 */\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { LeafNode } from '../LeafNode';\nimport { NamedNode, Node } from '../Node';\n\nimport { Index } from './Index';\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\nexport class PriorityIndex extends Index {\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 isDefinedOn(node: Node): boolean {\n return !node.getPriority().isEmpty();\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE));\n }\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 * @returns 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 source: OperationSource;\n\n type: OperationType;\n\n path: Path;\n\n operationForChild(childName: string): Operation | null;\n}\n\nexport interface OperationSource {\n fromUser: boolean;\n fromServer: boolean;\n queryId: string | null;\n tagged: boolean;\n}\n\nexport function newOperationSourceUser(): OperationSource {\n return {\n fromUser: true,\n fromServer: false,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServer(): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId: null,\n tagged: false\n };\n}\n\nexport function newOperationSourceServerTaggedQuery(\n queryId: string\n): OperationSource {\n return {\n fromUser: false,\n fromServer: true,\n queryId,\n tagged: true\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { Operation } from './operation/Operation';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport {\n View,\n viewAddEventRegistration,\n viewApplyOperation,\n viewGetCompleteServerCache,\n viewGetInitialEvents,\n viewIsEmpty,\n viewRemoveEventRegistration\n} from './view/View';\nimport { newViewCache } from './view/ViewCache';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren\n} from './WriteTree';\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 /**\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 readonly views: Map<string, View> = new Map();\n}\n\nexport function syncPointSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncPointGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport function syncPointIsEmpty(syncPoint: SyncPoint): boolean {\n return syncPoint.views.size === 0;\n}\n\nexport function syncPointApplyOperation(\n syncPoint: SyncPoint,\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 = syncPoint.views.get(queryId);\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return viewApplyOperation(\n view,\n operation,\n writesCache,\n optCompleteServerCache\n );\n } else {\n let events: Event[] = [];\n\n for (const view of syncPoint.views.values()) {\n events = events.concat(\n viewApplyOperation(view, operation, writesCache, optCompleteServerCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Get a view for the specified query.\n *\n * @param query - The query to return a view for\n * @param writesCache\n * @param serverCache\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointGetView(\n syncPoint: SyncPoint,\n query: QueryContext,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): View {\n const queryId = query._queryIdentifier;\n const view = syncPoint.views.get(queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writeTreeRefCalcCompleteEventCache(\n writesCache,\n serverCacheComplete ? serverCache : null\n );\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n } else if (serverCache instanceof ChildrenNode) {\n eventCache = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverCache\n );\n eventCacheComplete = false;\n } else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = newViewCache(\n new CacheNode(eventCache, eventCacheComplete, false),\n new CacheNode(serverCache, serverCacheComplete, false)\n );\n return new View(query, viewCache);\n }\n return view;\n}\n\n/**\n * Add an event callback for the specified query.\n *\n * @param query\n * @param eventRegistration\n * @param writesCache\n * @param serverCache - Complete server cache, if we have it.\n * @param serverCacheComplete\n * @returns Events to raise.\n */\nexport function syncPointAddEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n): Event[] {\n const view = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!syncPoint.views.has(query._queryIdentifier)) {\n syncPoint.views.set(query._queryIdentifier, view);\n }\n // This is guaranteed to exist now, we just created anything that was missing\n viewAddEventRegistration(view, eventRegistration);\n return viewGetInitialEvents(view, 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 eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns removed queries and any cancel events\n */\nexport function syncPointRemoveEventRegistration(\n syncPoint: SyncPoint,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n): { removed: QueryContext[]; events: Event[] } {\n const queryId = query._queryIdentifier;\n const removed: QueryContext[] = [];\n let cancelEvents: Event[] = [];\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\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 syncPoint.views.entries()) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(viewQueryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n } else {\n // remove the callback from the specific view.\n const view = syncPoint.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n viewRemoveEventRegistration(view, eventRegistration, cancelError)\n );\n if (viewIsEmpty(view)) {\n syncPoint.views.delete(queryId);\n\n // We'll deal with complete views later.\n if (!view.query._queryParams.loadsAllData()) {\n removed.push(view.query);\n }\n }\n }\n }\n\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\n // We removed our last complete view.\n removed.push(\n new (syncPointGetReferenceConstructor())(query._repo, query._path)\n );\n }\n\n return { removed, events: cancelEvents };\n}\n\nexport function syncPointGetQueryViews(syncPoint: SyncPoint): View[] {\n const result = [];\n for (const view of syncPoint.views.values()) {\n if (!view.query._queryParams.loadsAllData()) {\n result.push(view);\n }\n }\n return result;\n}\n\n/**\n * @param path - The path to the desired complete snapshot\n * @returns A complete cache, if it exists\n */\nexport function syncPointGetCompleteServerCache(\n syncPoint: SyncPoint,\n path: Path\n): Node | null {\n let serverCache: Node | null = null;\n for (const view of syncPoint.views.values()) {\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\n }\n return serverCache;\n}\n\nexport function syncPointViewForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): View | null {\n const params = query._queryParams;\n if (params.loadsAllData()) {\n return syncPointGetCompleteView(syncPoint);\n } else {\n const queryId = query._queryIdentifier;\n return syncPoint.views.get(queryId);\n }\n}\n\nexport function syncPointViewExistsForQuery(\n syncPoint: SyncPoint,\n query: QueryContext\n): boolean {\n return syncPointViewForQuery(syncPoint, query) != null;\n}\n\nexport function syncPointHasCompleteView(syncPoint: SyncPoint): boolean {\n return syncPointGetCompleteView(syncPoint) != null;\n}\n\nexport function syncPointGetCompleteView(syncPoint: SyncPoint): View | null {\n for (const view of syncPoint.views.values()) {\n if (view.query._queryParams.loadsAllData()) {\n return view;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ReferenceConstructor } from '../api/Reference';\n\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ListenComplete } from './operation/ListenComplete';\nimport { Merge } from './operation/Merge';\nimport {\n newOperationSourceServer,\n newOperationSourceServerTaggedQuery,\n newOperationSourceUser,\n Operation\n} from './operation/Operation';\nimport { Overwrite } from './operation/Overwrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport {\n SyncPoint,\n syncPointAddEventRegistration,\n syncPointApplyOperation,\n syncPointGetCompleteServerCache,\n syncPointGetCompleteView,\n syncPointGetQueryViews,\n syncPointGetView,\n syncPointHasCompleteView,\n syncPointIsEmpty,\n syncPointRemoveEventRegistration,\n syncPointViewExistsForQuery,\n syncPointViewForQuery\n} from './SyncPoint';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathGetFront,\n pathIsEmpty\n} from './util/Path';\nimport { each, errorForServerCode } from './util/util';\nimport { CacheNode } from './view/CacheNode';\nimport { Event } from './view/Event';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\nimport { View, viewGetCompleteNode, viewGetServerCache } from './view/View';\nimport {\n newWriteTree,\n WriteTree,\n writeTreeAddMerge,\n writeTreeAddOverwrite,\n writeTreeCalcCompleteEventCache,\n writeTreeChildWrites,\n writeTreeGetWrite,\n WriteTreeRef,\n writeTreeRefChild,\n writeTreeRemoveWrite\n} from './WriteTree';\n\nlet referenceConstructor: ReferenceConstructor;\n\nexport function syncTreeSetReferenceConstructor(\n val: ReferenceConstructor\n): void {\n assert(\n !referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n referenceConstructor = val;\n}\n\nfunction syncTreeGetReferenceConstructor(): ReferenceConstructor {\n assert(referenceConstructor, 'Reference.ts has not been loaded');\n return referenceConstructor;\n}\n\nexport interface ListenProvider {\n startListening(\n query: QueryContext,\n tag: number | null,\n hashFn: () => string,\n onComplete: (a: string, b?: unknown) => Event[]\n ): Event[];\n\n stopListening(a: QueryContext, b: number | null): void;\n}\n\n/**\n * Static tracker for next query tag.\n */\nlet syncTreeNextQueryTag_ = 1;\n\nexport function resetSyncTreeTag() {\n syncTreeNextQueryTag_ = 1;\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 */\nexport class SyncTree {\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n */\n syncPointTree_: ImmutableTree<SyncPoint> = new ImmutableTree<SyncPoint>(null);\n\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n pendingWriteTree_: WriteTree = newWriteTree();\n\n readonly tagToQueryMap: Map<number, string> = new Map();\n readonly queryToTagMap: Map<string, number> = new Map();\n\n /**\n * @param listenProvider_ - Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(public listenProvider_: ListenProvider) {}\n}\n\n/**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node,\n writeId: number,\n visible?: boolean\n): Event[] {\n // Record pending write.\n writeTreeAddOverwrite(\n syncTree.pendingWriteTree_,\n path,\n newData,\n writeId,\n visible\n );\n\n if (!visible) {\n return [];\n } else {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceUser(), path, newData)\n );\n }\n}\n\n/**\n * Apply the data from a user-generated update() call\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyUserMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n): Event[] {\n // Record pending merge.\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\n\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceUser(), 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 * @returns Events to raise.\n */\nexport function syncTreeAckUserWrite(\n syncTree: SyncTree,\n writeId: number,\n revert: boolean = false\n) {\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\n const needToReevaluate = writeTreeRemoveWrite(\n syncTree.pendingWriteTree_,\n writeId\n );\n if (!needToReevaluate) {\n return [];\n } else {\n let affectedTree = new ImmutableTree<boolean>(null);\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(newEmptyPath(), true);\n } else {\n each(write.children, (pathString: string) => {\n affectedTree = affectedTree.set(new Path(pathString), true);\n });\n }\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new AckUserWrite(write.path, affectedTree, revert)\n );\n }\n}\n\n/**\n * Apply new server data for the specified path..\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerOverwrite(\n syncTree: SyncTree,\n path: Path,\n newData: Node\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Overwrite(newOperationSourceServer(), path, newData)\n );\n}\n\n/**\n * Apply new server data to be merged in at the specified path.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyServerMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node }\n): Event[] {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new Merge(newOperationSourceServer(), path, changeTree)\n );\n}\n\n/**\n * Apply a listen complete for a query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyListenComplete(\n syncTree: SyncTree,\n path: Path\n): Event[] {\n return syncTreeApplyOperationToSyncPoints_(\n syncTree,\n new ListenComplete(newOperationSourceServer(), path)\n );\n}\n\n/**\n * Apply a listen complete for a tagged query\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedListenComplete(\n syncTree: SyncTree,\n path: Path,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new ListenComplete(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath\n );\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\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 * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\n * deduping needs to take place. This flag allows toggling of that behavior\n * @returns Cancel events, if cancelError was provided.\n */\nexport function syncTreeRemoveEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration | null,\n cancelError?: Error,\n skipListenerDedup = false\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 = syncTree.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 syncPointViewExistsForQuery(maybeSyncPoint, query))\n ) {\n const removedAndEvents = syncPointRemoveEventRegistration(\n maybeSyncPoint,\n query,\n eventRegistration,\n cancelError\n );\n if (syncPointIsEmpty(maybeSyncPoint)) {\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\n }\n\n const removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n\n if (!skipListenerDedup) {\n /**\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\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._queryParams.loadsAllData();\n });\n const covered = syncTree.syncPointTree_.findOnPath(\n path,\n (relativePath, parentSyncPoint) =>\n syncPointHasCompleteView(parentSyncPoint)\n );\n\n if (removingDefault && !covered) {\n const subtree = syncTree.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 = syncTreeCollectDistinctViewsForSubTree_(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.query;\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(newQuery),\n syncTreeTagForQuery(syncTree, newQuery),\n listener.hashFn,\n listener.onComplete\n );\n }\n }\n // Otherwise there's nothing below us, so nothing we need to start listening on\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 syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(query),\n defaultTag\n );\n } else {\n removed.forEach((queryToRemove: QueryContext) => {\n const tagToRemove = syncTree.queryToTagMap.get(\n syncTreeMakeQueryKey_(queryToRemove)\n );\n syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToRemove),\n tagToRemove\n );\n });\n }\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n syncTreeRemoveTags_(syncTree, removed);\n } else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n}\n\n/**\n * Apply new server data for the specified tagged query.\n *\n * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryOverwrite(\n syncTree: SyncTree,\n path: Path,\n snap: Node,\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey != null) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const op = new Overwrite(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n snap\n );\n return syncTreeApplyTaggedOperation_(syncTree, 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 * @returns Events to raise.\n */\nexport function syncTreeApplyTaggedQueryMerge(\n syncTree: SyncTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n tag: number\n): Event[] {\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\n if (queryKey) {\n const r = syncTreeParseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = newRelativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(\n newOperationSourceServerTaggedQuery(queryId),\n relativePath,\n changeTree\n );\n return syncTreeApplyTaggedOperation_(syncTree, 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 * @returns Events to raise.\n */\nexport function syncTreeAddEventRegistration(\n syncTree: SyncTree,\n query: QueryContext,\n eventRegistration: EventRegistration,\n skipSetupListener = false\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 syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\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 = syncTree.syncPointTree_.subtree(path);\n subtree.foreachChild((childName, childSyncPoint) => {\n const completeCache = syncPointGetCompleteServerCache(\n childSyncPoint,\n newEmptyPath()\n );\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(\n childName,\n completeCache\n );\n }\n });\n }\n\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = syncTreeMakeQueryKey_(query);\n assert(\n !syncTree.queryToTagMap.has(queryKey),\n 'View does not exist, but we have a tag'\n );\n const tag = syncTreeGetNextQueryTag_();\n syncTree.queryToTagMap.set(queryKey, tag);\n syncTree.tagToQueryMap.set(tag, queryKey);\n }\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\n let events = syncPointAddEventRegistration(\n syncPoint,\n query,\n eventRegistration,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\n const view = syncPointViewForQuery(syncPoint, query);\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\n }\n return events;\n}\n\n/**\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\n * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->\n * <incremented total> as the write is applied locally and then acknowledged at the server.\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 */\nexport function syncTreeCalcCompleteEventCache(\n syncTree: SyncTree,\n path: Path,\n writeIdsToExclude?: number[]\n): Node {\n const includeHiddenSets = true;\n const writeTree = syncTree.pendingWriteTree_;\n const serverCache = syncTree.syncPointTree_.findOnPath(\n path,\n (pathSoFar, syncPoint) => {\n const relativePath = newRelativePath(pathSoFar, path);\n const serverCache = syncPointGetCompleteServerCache(\n syncPoint,\n relativePath\n );\n if (serverCache) {\n return serverCache;\n }\n }\n );\n return writeTreeCalcCompleteEventCache(\n writeTree,\n path,\n serverCache,\n writeIdsToExclude,\n includeHiddenSets\n );\n}\n\nexport function syncTreeGetServerValue(\n syncTree: SyncTree,\n query: QueryContext\n): Node | null {\n const path = query._path;\n let serverCache: Node | null = null;\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 syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\n const relativePath = newRelativePath(pathToSyncPoint, path);\n serverCache =\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\n });\n let syncPoint = syncTree.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\n } else {\n serverCache =\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n const serverCacheComplete = serverCache != null;\n const serverCacheNode: CacheNode | null = serverCacheComplete\n ? new CacheNode(serverCache, true, false)\n : null;\n const writesCache: WriteTreeRef | null = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n query._path\n );\n const view: View = syncPointGetView(\n syncPoint,\n query,\n writesCache,\n serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE,\n serverCacheComplete\n );\n return viewGetCompleteNode(view);\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 */\nfunction syncTreeApplyOperationToSyncPoints_(\n syncTree: SyncTree,\n operation: Operation\n): Event[] {\n return syncTreeApplyOperationHelper_(\n operation,\n syncTree.syncPointTree_,\n /*serverCache=*/ null,\n writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())\n );\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree<SyncPoint>,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n if (pathIsEmpty(operation.path)) {\n return syncTreeApplyOperationDescendantsHelper_(\n operation,\n syncPointTree,\n serverCache,\n writesCache\n );\n } else {\n const syncPoint = syncPointTree.get(newEmptyPath());\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 = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\n }\n\n let events: Event[] = [];\n const childName = pathGetFront(operation.path);\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 = writeTreeRefChild(writesCache, childName);\n events = events.concat(\n syncTreeApplyOperationHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\n}\n\n/**\n * Recursive helper for applyOperationToSyncPoints_\n */\nfunction syncTreeApplyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree<SyncPoint>,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n): Event[] {\n const syncPoint = syncPointTree.get(newEmptyPath());\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 = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\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 = writeTreeRefChild(writesCache, childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(\n syncTreeApplyOperationDescendantsHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n });\n\n if (syncPoint) {\n events = events.concat(\n syncPointApplyOperation(syncPoint, operation, writesCache, serverCache)\n );\n }\n\n return events;\n}\n\nfunction syncTreeCreateListenerForView_(\n syncTree: SyncTree,\n view: View\n): { hashFn(): string; onComplete(a: string, b?: unknown): Event[] } {\n const query = view.query;\n const tag = syncTreeTagForQuery(syncTree, query);\n\n return {\n hashFn: () => {\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status: string): Event[] => {\n if (status === 'ok') {\n if (tag) {\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\n } else {\n return syncTreeApplyListenComplete(syncTree, 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 syncTreeRemoveEventRegistration(\n syncTree,\n query,\n /*eventRegistration*/ null,\n error\n );\n }\n }\n };\n}\n\n/**\n * Return the tag associated with the given query.\n */\nexport function syncTreeTagForQuery(\n syncTree: SyncTree,\n query: QueryContext\n): number | null {\n const queryKey = syncTreeMakeQueryKey_(query);\n return syncTree.queryToTagMap.get(queryKey);\n}\n\n/**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n */\nfunction syncTreeMakeQueryKey_(query: QueryContext): string {\n return query._path.toString() + '$' + query._queryIdentifier;\n}\n\n/**\n * Return the query associated with the given tag, if we have one\n */\nfunction syncTreeQueryKeyForTag_(\n syncTree: SyncTree,\n tag: number\n): string | null {\n return syncTree.tagToQueryMap.get(tag);\n}\n\n/**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n */\nfunction syncTreeParseQueryKey_(queryKey: string): {\n queryId: string;\n path: Path;\n} {\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 * A helper method to apply tagged operations\n */\nfunction syncTreeApplyTaggedOperation_(\n syncTree: SyncTree,\n queryPath: Path,\n operation: Operation\n): Event[] {\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = writeTreeChildWrites(\n syncTree.pendingWriteTree_,\n queryPath\n );\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\n}\n\n/**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n */\nfunction syncTreeCollectDistinctViewsForSubTree_(\n subtree: ImmutableTree<SyncPoint>\n): View[] {\n return subtree.fold<View[]>((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\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 = syncPointGetQueryViews(maybeChildSyncPoint);\n }\n each(childMap, (_key: string, childViews: View[]) => {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n}\n\n/**\n * Normalizes a query to a query we send the server for listening\n *\n * @returns The normalized query\n */\nfunction syncTreeQueryForListening_(query: QueryContext): QueryContext {\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\n } else {\n return query;\n }\n}\n\nfunction syncTreeRemoveTags_(syncTree: SyncTree, queries: QueryContext[]) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery._queryParams.loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\n syncTree.queryToTagMap.delete(removedQueryKey);\n syncTree.tagToQueryMap.delete(removedQueryTag);\n }\n }\n}\n\n/**\n * Static accessor for query tags.\n */\nfunction syncTreeGetNextQueryTag_(): number {\n return syncTreeNextQueryTag_++;\n}\n\n/**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @returns This method can return events to support synchronous data sources\n */\nfunction syncTreeSetupListener_(\n syncTree: SyncTree,\n query: QueryContext,\n view: View\n): Event[] {\n const path = query._path;\n const tag = syncTreeTagForQuery(syncTree, query);\n const listener = syncTreeCreateListenerForView_(syncTree, view);\n\n const events = syncTree.listenProvider_.startListening(\n syncTreeQueryForListening_(query),\n tag,\n listener.hashFn,\n listener.onComplete\n );\n\n const subtree = syncTree.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 !syncPointHasCompleteView(subtree.value),\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<QueryContext[]>(\n (relativePath, maybeChildSyncPoint, childMap) => {\n if (\n !pathIsEmpty(relativePath) &&\n maybeChildSyncPoint &&\n syncPointHasCompleteView(maybeChildSyncPoint)\n ) {\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\n } else {\n // No default listener here, flatten any deeper queries into an array\n let queries: QueryContext[] = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(\n syncPointGetQueryViews(maybeChildSyncPoint).map(\n view => view.query\n )\n );\n }\n each(childMap, (_key: string, childQueries: QueryContext[]) => {\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 syncTree.listenProvider_.stopListening(\n syncTreeQueryForListening_(queryToStop),\n syncTreeTagForQuery(syncTree, queryToStop)\n );\n }\n }\n return events;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { repoManagerDatabaseFromApp } from './api/Database';\n\nexport function registerDatabase(variant?: string): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'database',\n (container, { instanceIdentifier: url }) => {\n const app = container.getProvider('app').getImmediate()!;\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n return repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url\n );\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport {\n assert,\n base64,\n Sha1,\n stringToByteArray,\n stringify,\n isNodeSdk\n} from '@firebase/util';\n\nimport { SessionStorage } from '../storage/storage';\nimport { QueryContext } from '../view/EventRegistration';\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 */\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 str - The string to hash\n * @returns {!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\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 */\nexport let logger: ((a: string) => void) | null = null;\n\n/**\n * Flag to check for log availability on first log message\n */\nlet firstLog_ = true;\n\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param logger_ - A flag to turn on logging, or a custom logger\n * @param 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\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\nexport const logWrapper = function (\n prefix: string\n): (...varArgs: unknown[]) => void {\n return function (...varArgs: unknown[]) {\n log(prefix, ...varArgs);\n };\n};\n\nexport const error = function (...varArgs: string[]) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\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\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\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 */\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\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 */\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 */\nexport const MAX_NAME = '[MAX_NAME]';\n\n/**\n * Compares valid Firebase key names, plus min and max name\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 * @returns {!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\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\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 str - The string\n * @param segsize - The maximum number of chars in the string.\n * @returns 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 callback - Callback function.\n * @param context - Optional context to bind to.\n *\n */\nexport const bindCallback = function (\n callback: (a: unknown) => void,\n context?: object | null\n): (a: unknown) => void {\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 v - A double\n *\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 */\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 */\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 */\nexport function errorForServerCode(code: string, query: QueryContext): 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 */\nexport const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\n\n/**\n * For use in keys, the minimum possible 32-bit integer.\n */\nexport const INTEGER_32_MIN = -2147483648;\n\n/**\n * For use in kyes, the maximum possible 32-bit integer.\n */\nexport const INTEGER_32_MAX = 2147483647;\n\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n */\nexport const tryParseInt = function (str: string): number | null {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\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 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 callback - Optional onComplete callback.\n * @param varArgs - Arbitrary args to be passed to opt_onComplete\n */\nexport const callUserCallback = function (\n // eslint-disable-next-line @typescript-eslint/ban-types\n callback?: Function | null,\n ...varArgs: unknown[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(() => {\n callback(...varArgs);\n });\n }\n};\n\n/**\n * @returns {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 */\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 fn - Function to run.\n * @param time - Milliseconds to wait before running.\n * @returns The setTimeout() return value.\n */\nexport const setTimeoutNonBlocking = function (\n fn: () => void,\n time: number\n): number | object {\n const timeout: number | object = setTimeout(fn, time);\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\n if (\n typeof timeout === 'number' &&\n // @ts-ignore Is only defined in Deno environments.\n typeof Deno !== 'undefined' &&\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno['unrefTimer']\n ) {\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\n Deno.unrefTimer(timeout);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else 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\n return timeout;\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { warn } from './util/util';\n\n/**\n * Abstraction around AppCheck's token fetching capabilities.\n */\nexport class AppCheckTokenProvider {\n private appCheck?: FirebaseAppCheckInternal;\n constructor(\n private appName_: string,\n private appCheckProvider?: Provider<AppCheckInternalComponentName>\n ) {\n this.appCheck = appCheckProvider?.getImmediate({ optional: true });\n if (!this.appCheck) {\n appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck));\n }\n }\n\n getToken(forceRefresh?: boolean): Promise<AppCheckTokenResult> {\n if (!this.appCheck) {\n return new Promise<AppCheckTokenResult>((resolve, reject) => {\n // Support delayed initialization of FirebaseAppCheck. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // AppCheck and ensures that all requests are authenticated if a token\n // becomes available before the timoeout below expires.\n setTimeout(() => {\n if (this.appCheck) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n return this.appCheck.getToken(forceRefresh);\n }\n\n addTokenChangeListener(listener: AppCheckTokenListener) {\n this.appCheckProvider\n ?.get()\n .then(appCheck => appCheck.addTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n warn(\n `Provided AppCheck credentials for the app named \"${this.appName_}\" ` +\n 'are invalid. This usually indicates your app was not initialized correctly.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/app-types/private';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { log, warn } from './util/util';\n\nexport interface AuthTokenProvider {\n getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData>;\n addTokenChangeListener(listener: (token: string | null) => void): void;\n removeTokenChangeListener(listener: (token: string | null) => void): void;\n notifyForInvalidToken(): void;\n}\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class FirebaseAuthTokenProvider implements AuthTokenProvider {\n private auth_: FirebaseAuthInternal | null = null;\n\n constructor(\n private appName_: string,\n private firebaseOptions_: object,\n private authProvider_: Provider<FirebaseAuthInternalName>\n ) {\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.onInit(auth => (this.auth_ = auth));\n }\n }\n\n getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData> {\n if (!this.auth_) {\n return new Promise<FirebaseAuthTokenData>((resolve, reject) => {\n // Support delayed initialization of FirebaseAuth. This allows our\n // customers to initialize the RTDB SDK before initializing Firebase\n // Auth and ensures that all requests are authenticated if a token\n // becomes available before the timoeout below expires.\n setTimeout(() => {\n if (this.auth_) {\n this.getToken(forceRefresh).then(resolve, reject);\n } else {\n resolve(null);\n }\n }, 0);\n });\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): 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 this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {\n this.authProvider_\n .get()\n .then(auth => auth.removeAuthTokenListener(listener));\n }\n\n notifyForInvalidToken(): void {\n let errorMessage =\n 'Provided authentication credentials for the app named \"' +\n this.appName_ +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.firebaseOptions_) {\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.firebaseOptions_) {\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/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\nexport class EmulatorTokenProvider implements AuthTokenProvider {\n /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\n static OWNER = 'owner';\n\n constructor(private accessToken: string) {}\n\n getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData> {\n return Promise.resolve({\n accessToken: this.accessToken\n });\n }\n\n addTokenChangeListener(listener: (token: string | null) => void): void {\n // Invoke the listener immediately to match the behavior in Firebase Auth\n // (see packages/auth/src/auth.js#L1807)\n listener(this.accessToken);\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void): void {}\n\n notifyForInvalidToken(): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\n// firebase.corp.google.com\nexport const FORGE_DOMAIN_RE =\n /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\n\nexport const LAST_SESSION_PARAM = 'ls';\n\nexport const APPLICATION_ID_PARAM = 'p';\n\nexport const APP_CHECK_TOKEN_PARAM = 'ac';\n\nexport const WEBSOCKET = 'websocket';\n\nexport const LONG_POLLING = 'long_polling';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\n\nimport { PersistentStorage } from './storage/storage';\nimport { each } from './util/util';\n\n/**\n * A class that holds metadata about a Repo object\n */\nexport class RepoInfo {\n private _host: string;\n private _domain: string;\n internalHost: string;\n\n /**\n * @param host - Hostname portion of the url for the repo\n * @param secure - Whether or not this repo is accessed over ssl\n * @param namespace - The namespace represented by the repo\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\n * @param persistenceKey - Override the default session persistence storage key\n */\n constructor(\n host: string,\n public readonly secure: boolean,\n public readonly namespace: string,\n public readonly webSocketOnly: boolean,\n public readonly nodeAdmin: boolean = false,\n public readonly persistenceKey: string = '',\n public readonly includeNamespaceInQueryParams: boolean = false,\n public readonly isUsingEmulator: 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 isCacheableHost(): boolean {\n return this.internalHost.substr(0, 2) === 's-';\n }\n\n isCustomHost() {\n return (\n this._domain !== 'firebaseio.com' &&\n this._domain !== 'firebaseio-demo.com'\n );\n }\n\n get host() {\n return this._host;\n }\n\n set host(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 toString(): string {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n\n toURLString(): string {\n const protocol = this.secure ? 'https://' : 'http://';\n const query = this.includeNamespaceInQueryParams\n ? `?ns=${this.namespace}`\n : '';\n return `${protocol}${this.host}/${query}`;\n }\n}\n\nfunction repoInfoNeedsQueryParam(repoInfo: RepoInfo): boolean {\n return (\n repoInfo.host !== repoInfo.internalHost ||\n repoInfo.isCustomHost() ||\n repoInfo.includeNamespaceInQueryParams\n );\n}\n\n/**\n * Returns the websocket URL for this repo\n * @param repoInfo - RepoInfo object\n * @param type - of connection\n * @param params - list\n * @returns The URL for this repo\n */\nexport function repoInfoConnectionURL(\n repoInfo: RepoInfo,\n type: string,\n params: { [k: string]: string }\n): 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 (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\n } else if (type === LONG_POLLING) {\n connURL =\n (repoInfo.secure ? 'https://' : 'http://') +\n repoInfo.internalHost +\n '/.lp?';\n } else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (repoInfoNeedsQueryParam(repoInfo)) {\n params['ns'] = repoInfo.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 * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deepCopy, contains } from '@firebase/util';\n\n/**\n * Tracks a collection of stats.\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport { StatsCollection } from './StatsCollection';\n\nconst collections: { [k: string]: StatsCollection } = {};\nconst reporters: { [k: string]: unknown } = {};\n\nexport function statsManagerGetCollection(repoInfo: RepoInfo): StatsCollection {\n const hashString = repoInfo.toString();\n\n if (!collections[hashString]) {\n collections[hashString] = new StatsCollection();\n }\n\n return collections[hashString];\n}\n\nexport function statsManagerGetOrCreateReporter<T>(\n repoInfo: RepoInfo,\n creatorFunction: () => T\n): T {\n const hashString = repoInfo.toString();\n\n if (!reporters[hashString]) {\n reporters[hashString] = creatorFunction();\n }\n\n return reporters[hashString] as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 */\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 */\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Encode, isNodeSdk, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport {\n executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\n\nimport {\n APP_CHECK_TOKEN_PARAM,\n APPLICATION_ID_PARAM,\n FORGE_DOMAIN_RE,\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 { PacketReceiver } from './polling/PacketReceiver';\nimport { Transport } from './Transport';\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 */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n\n/**\n * How long to wait before aborting a long-polling connection attempt.\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n\n/**\n * This class manages a single long-polling connection.\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 connId An identifier for this connection, used for logging\n * @param repoInfo The info for the endpoint to send data to.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The AppCheck token for this client.\n * @param authToken The AuthToken to use for this connection.\n * @param transportSessionId Optional transportSessionid if we are\n * reconnecting for an existing transport session\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\n * already created a connection previously\n */\n constructor(\n public connId: string,\n public repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n public transportSessionId?: string,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper(connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.urlFn = (params: { [k: string]: string }) => {\n // Always add the token if we have one.\n if (this.appCheckToken) {\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\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.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[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 (this.applicationId) {\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\n }\n if (this.appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\n }\n if (\n typeof location !== 'undefined' &&\n location.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\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 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 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 */\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 */\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 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 */\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 */\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/naming-convention\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 *********************************************************************************************/\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[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 */\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 textContent seems to be the safest way to do this.\n this.myIFrame.doc.body.textContent = '';\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 id - The ID of this connection\n * @param 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 url - The URL of the script tag.\n * @param serial - The serial number of the request.\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 url - The URL for the script tag source.\n * @param 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 =\n 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isNodeSdk, jsonEval, stringify } from '@firebase/util';\n\nimport { RepoInfo, repoInfoConnectionURL } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { statsManagerGetCollection } from '../core/stats/StatsManager';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { logWrapper, splitStringBySize } from '../core/util/util';\nimport { SDK_VERSION } from '../core/version';\n\nimport {\n APPLICATION_ID_PARAM,\n APP_CHECK_TOKEN_PARAM,\n FORGE_DOMAIN_RE,\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 { Transport } from './Transport';\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 */\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 private nodeAdmin: boolean;\n\n /**\n * @param connId identifier for this transport\n * @param repoInfo The info for the websocket endpoint.\n * @param applicationId The Firebase App ID for this project.\n * @param appCheckToken The App Check Token for this client.\n * @param authToken The Auth Token for this client.\n * @param transportSessionId Optional transportSessionId if this is connecting\n * to an existing transport session\n * @param lastSessionId Optional lastSessionId if there was a previous\n * connection\n */\n constructor(\n public connId: string,\n repoInfo: RepoInfo,\n private applicationId?: string,\n private appCheckToken?: string,\n private authToken?: string,\n transportSessionId?: string,\n lastSessionId?: string\n ) {\n this.log_ = logWrapper(this.connId);\n this.stats_ = statsManagerGetCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(\n repoInfo,\n transportSessionId,\n lastSessionId,\n appCheckToken,\n applicationId\n );\n this.nodeAdmin = repoInfo.nodeAdmin;\n }\n\n /**\n * @param repoInfo - The info for the websocket endpoint.\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\n * @returns connection url\n */\n private static connectionURL_(\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string,\n appCheckToken?: string,\n applicationId?: 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.hostname &&\n FORGE_DOMAIN_RE.test(location.hostname)\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 if (appCheckToken) {\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\n }\n if (applicationId) {\n urlParams[APPLICATION_ID_PARAM] = applicationId;\n }\n\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\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 let options: { [k: string]: object };\n if (isNodeSdk()) {\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\n // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>\n options = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\n 'X-Firebase-GMPID': this.applicationId || ''\n }\n };\n\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\n // Note that we send the credentials here even if they aren't admin credentials, which is\n // not a problem.\n // Note that this header is just used to bypass appcheck, and the token should still be sent\n // through the websocket connection once it is established.\n if (this.authToken) {\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\n }\n if (this.appCheckToken) {\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\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 } 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 */\n static responsesRequiredToBeHealthy = 2;\n\n /**\n * Time to wait for the connection te become healthy before giving up.\n */\n static healthyTimeout = 30000;\n\n /**\n * Returns true if we previously failed to connect with this transport.\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 frameCount - The number of frames we are expecting from the server\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 * @returns Any remaining data to be process, or null if there is none\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 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 str - String to send.\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { warn } from '../core/util/util';\n\nimport { BrowserPollConnection } from './BrowserPollConnection';\nimport { TransportConstructor } from './Transport';\nimport { WebSocketConnection } from './WebSocketConnection';\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 */\nexport class TransportManager {\n private transports_: TransportConstructor[];\n\n // Keeps track of whether the TransportManager has already chosen a transport to use\n static globalTransportInitialized_ = false;\n\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n\n /**\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\n * TransportManager has already set up transports_\n */\n static get IS_TRANSPORT_INITIALIZED() {\n return this.globalTransportInitialized_;\n }\n\n /**\n * @param repoInfo - Metadata around the namespace we're connecting to\n */\n constructor(repoInfo: RepoInfo) {\n this.initTransports_(repoInfo);\n }\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 TransportManager.globalTransportInitialized_ = true;\n }\n }\n\n /**\n * @returns The constructor for the 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 * @returns The constructor for the next 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../core/RepoInfo';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { Indexable } from '../core/util/misc';\nimport {\n error,\n logWrapper,\n requireKey,\n setTimeoutNonBlocking,\n warn\n} from '../core/util/util';\n\nimport { PROTOCOL_VERSION } from './Constants';\nimport { Transport, TransportConstructor } from './Transport';\nimport { TransportManager } from './TransportManager';\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 */\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 id - an id for this connection\n * @param repoInfo_ - the info for the endpoint to connect to\n * @param applicationId_ - the Firebase App ID for this project\n * @param appCheckToken_ - The App Check Token for this device.\n * @param authToken_ - The auth token for this session.\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param 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 applicationId_: string | undefined,\n private appCheckToken_: string | undefined,\n private authToken_: string | undefined,\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 */\n private start_(): void {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n null,\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 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 * @param 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 const handshakePayload = {\n ...(payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n })\n };\n if (this.repoInfo_.isUsingEmulator) {\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\n handshakePayload.h = this.repoInfo_.host;\n }\n this.onHandshake_(handshakePayload);\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 * @param handshake - The handshake data returned from the server\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_.host = 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.applicationId_,\n this.appCheckToken_,\n this.authToken_,\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_.host = 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 * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\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 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 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryContext } from './view/EventRegistration';\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 abstract listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ): void;\n\n /**\n * Remove a listen.\n */\n abstract unlisten(query: QueryContext, tag: number | null): void;\n\n /**\n * Get the server value satisfying this query.\n */\n abstract get(query: QueryContext): Promise<string>;\n\n put(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {}\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 token - The authentication token\n */\n refreshAuthToken(token: string) {}\n\n /**\n * Refreshes the app check token for the current connection.\n * @param token The app check token\n */\n refreshAppCheckToken(token: string) {}\n\n onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n reportStats(stats: { [k: string]: unknown }) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 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 * @returns {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 */\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, isMobileCordova } from '@firebase/util';\n\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 */\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 getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n\n currentlyOnline(): boolean {\n return this.online_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringLength } from '@firebase/util';\n\nimport { nameCompare } from './util';\n\n/** Maximum key depth. */\nconst MAX_PATH_DEPTH = 32;\n\n/** Maximum number of (UTF8) bytes in a Firebase path. */\nconst MAX_PATH_LENGTH_BYTES = 768;\n\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 pieces_: string[];\n pieceNum_: number;\n\n /**\n * @param pathOrString - Path string to parse, or another path, or the raw\n * tokens array\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 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\nexport function newEmptyPath(): Path {\n return new Path('');\n}\n\nexport function pathGetFront(path: Path): string | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n return path.pieces_[path.pieceNum_];\n}\n\n/**\n * @returns The number of segments in this path\n */\nexport function pathGetLength(path: Path): number {\n return path.pieces_.length - path.pieceNum_;\n}\n\nexport function pathPopFront(path: Path): Path {\n let pieceNum = path.pieceNum_;\n if (pieceNum < path.pieces_.length) {\n pieceNum++;\n }\n return new Path(path.pieces_, pieceNum);\n}\n\nexport function pathGetBack(path: Path): string | null {\n if (path.pieceNum_ < path.pieces_.length) {\n return path.pieces_[path.pieces_.length - 1];\n }\n\n return null;\n}\n\nexport function pathToUrlEncodedString(path: Path): string {\n let pathString = '';\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n if (path.pieces_[i] !== '') {\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\n }\n }\n\n return pathString || '/';\n}\n\n/**\n * Shallow copy of the parts of the path.\n *\n */\nexport function pathSlice(path: Path, begin: number = 0): string[] {\n return path.pieces_.slice(path.pieceNum_ + begin);\n}\n\nexport function pathParent(path: Path): Path | null {\n if (path.pieceNum_ >= path.pieces_.length) {\n return null;\n }\n\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n return new Path(pieces, 0);\n}\n\nexport function pathChild(path: Path, childPathObj: string | Path): Path {\n const pieces = [];\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\n pieces.push(path.pieces_[i]);\n }\n\n if (childPathObj instanceof Path) {\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\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 * @returns True if there are no segments in this path\n */\nexport function pathIsEmpty(path: Path): boolean {\n return path.pieceNum_ >= path.pieces_.length;\n}\n\n/**\n * @returns The path from outerPath to innerPath\n */\nexport function newRelativePath(outerPath: Path, innerPath: Path): Path {\n const outer = pathGetFront(outerPath),\n inner = pathGetFront(innerPath);\n if (outer === null) {\n return innerPath;\n } else if (outer === inner) {\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\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 * @returns -1, 0, 1 if left is less, equal, or greater than the right.\n */\nexport function pathCompare(left: Path, right: Path): number {\n const leftKeys = pathSlice(left, 0);\n const rightKeys = pathSlice(right, 0);\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 * @returns true if paths are the same.\n */\nexport function pathEquals(path: Path, other: Path): boolean {\n if (pathGetLength(path) !== pathGetLength(other)) {\n return false;\n }\n\n for (\n let i = path.pieceNum_, j = other.pieceNum_;\n i <= path.pieces_.length;\n i++, j++\n ) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * @returns True if this path is a parent of (or the same as) other\n */\nexport function pathContains(path: Path, other: Path): boolean {\n let i = path.pieceNum_;\n let j = other.pieceNum_;\n if (pathGetLength(path) > pathGetLength(other)) {\n return false;\n }\n while (i < path.pieces_.length) {\n if (path.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n}\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 parts_: string[];\n /** Initialize to number of '/' chars needed in path. */\n byteLength_: number;\n\n /**\n * @param path - Initial Path.\n * @param errorPrefix_ - Prefix for any error messages.\n */\n constructor(path: Path, public errorPrefix_: string) {\n this.parts_ = pathSlice(path, 0);\n /** 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 validationPathCheckValid(this);\n }\n}\n\nexport function validationPathPush(\n validationPath: ValidationPath,\n child: string\n): void {\n // Count the needed '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ += 1;\n }\n validationPath.parts_.push(child);\n validationPath.byteLength_ += stringLength(child);\n validationPathCheckValid(validationPath);\n}\n\nexport function validationPathPop(validationPath: ValidationPath): void {\n const last = validationPath.parts_.pop();\n validationPath.byteLength_ -= stringLength(last);\n // Un-count the previous '/'\n if (validationPath.parts_.length > 0) {\n validationPath.byteLength_ -= 1;\n }\n}\n\nfunction validationPathCheckValid(validationPath: ValidationPath): void {\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'has a key path longer than ' +\n MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n validationPath.byteLength_ +\n ').'\n );\n }\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\n throw new Error(\n validationPath.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n validationPathToErrorString(validationPath)\n );\n }\n}\n\n/**\n * String for use in error messages - uses '.' notation for path.\n */\nexport function validationPathToErrorString(\n validationPath: ValidationPath\n): string {\n if (validationPath.parts_.length === 0) {\n return '';\n }\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { EventEmitter } from './EventEmitter';\n\ndeclare const document: Document;\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 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n Deferred,\n isEmpty,\n isMobileCordova,\n isNodeSdk,\n isReactNative,\n isValidFormat,\n safeGet,\n stringify,\n isAdmin\n} from '@firebase/util';\n\nimport { Connection } from '../realtime/Connection';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { OnlineMonitor } from './util/OnlineMonitor';\nimport { Path } from './util/Path';\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { SDK_VERSION } from './version';\nimport { QueryContext } from './view/EventRegistration';\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_TOKEN_THRESHOLD = 3;\n\ninterface ListenSpec {\n onComplete(s: string, p?: unknown): void;\n\n hashFn(): string;\n\n query: QueryContext;\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\ninterface OutstandingGet {\n request: object;\n onComplete: (response: { [k: string]: unknown }) => 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 private readonly listens: Map<\n /* path */ string,\n Map</* queryId */ string, ListenSpec>\n > = new Map();\n private outstandingPuts_: OutstandingPut[] = [];\n private outstandingGets_: OutstandingGet[] = [];\n private outstandingPutCount_ = 0;\n private outstandingGetCount_ = 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 appCheckToken_: string | null = null;\n private forceTokenRefresh_ = false;\n private invalidAuthTokenCount_ = 0;\n private invalidAppCheckTokenCount_ = 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 * @param repoInfo_ - Data about the namespace we are connecting to\n * @param applicationId_ - The Firebase App ID for this project\n * @param onDataUpdate_ - A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private applicationId_: string,\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 appCheckTokenProvider_: AppCheckTokenProvider,\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\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 get(query: QueryContext): Promise<string> {\n this.initConnection_();\n\n const deferred = new Deferred<string>();\n const request = {\n p: query._path.toString(),\n q: query._queryObject\n };\n const outstandingGet = {\n action: 'g',\n request,\n onComplete: (message: { [k: string]: unknown }) => {\n const payload = message['d'] as string;\n if (message['s'] === 'ok') {\n deferred.resolve(payload);\n } else {\n deferred.reject(payload);\n }\n }\n };\n this.outstandingGets_.push(outstandingGet);\n this.outstandingGetCount_++;\n const index = this.outstandingGets_.length - 1;\n\n if (this.connected_) {\n this.sendGet_(index);\n }\n\n return deferred.promise;\n }\n\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n this.initConnection_();\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._queryParams.isDefault() || !query._queryParams.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 sendGet_(index: number) {\n const get = this.outstandingGets_[index];\n this.sendRequest('g', get.request, (message: { [k: string]: unknown }) => {\n delete this.outstandingGets_[index];\n this.outstandingGetCount_--;\n if (this.outstandingGetCount_ === 0) {\n this.outstandingGets_ = [];\n }\n if (get.onComplete) {\n get.onComplete(message);\n }\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: QueryContext) {\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\": \"' + query._queryParams.getIndex().toString() + '\"';\n const indexPath = query._path.toString();\n warn(\n `Using an unspecified index. Your data will be downloaded and ` +\n `filtered on the client. Consider adding ${indexSpec} at ` +\n `${indexPath} to your security rules for better performance.`\n );\n }\n }\n }\n\n 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 refreshAppCheckToken(token: string | null) {\n this.appCheckToken_ = token;\n this.log_('App check token refreshed');\n if (this.appCheckToken_) {\n this.tryAppCheck();\n } else {\n //If we're connected we want to let the server know to unauthenticate us.\n //If we're not connected, simply delete the credential so we dont become\n // authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unappeck', {}, () => {});\n }\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 * Attempts to authenticate with the given token. If the authentication\n * attempt fails, it's triggered like the token was revoked (the connection is\n * closed).\n */\n tryAppCheck() {\n if (this.connected_ && this.appCheckToken_) {\n this.sendRequest(\n 'appcheck',\n { 'token': this.appCheckToken_ },\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || 'error';\n if (status === 'ok') {\n this.invalidAppCheckTokenCount_ = 0;\n } else {\n this.onAppCheckRevoked_(status, data);\n }\n }\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n unlisten(query: QueryContext, 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._queryParams.isDefault() || !query._queryParams.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 onDisconnectPut(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\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 onDisconnectMerge(\n pathString: string,\n data: unknown,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\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 onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {\n this.initConnection_();\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 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 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 this.initConnection_();\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 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 === 'apc') {\n this.onAppCheckRevoked_(\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 initConnection_() {\n if (!this.realtime_ && this.firstConnection_) {\n this.scheduleConnect_(0);\n }\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 async 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 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 try {\n // First fetch auth and app check token, and establish connection after\n // fetching the token was successful\n const [authToken, appCheckToken] = await Promise.all([\n this.authTokenProvider_.getToken(forceRefresh),\n this.appCheckTokenProvider_.getToken(forceRefresh)\n ]);\n\n if (!canceled) {\n log('getToken() completed. Creating connection.');\n this.authToken_ = authToken && authToken.accessToken;\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\n connection = new Connection(\n connId,\n this.repoInfo_,\n this.applicationId_,\n this.appCheckToken_,\n this.authToken_,\n onDataMessage,\n onReady,\n onDisconnect,\n /* onKill= */ reason => {\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\n },\n lastSessionId\n );\n } else {\n log('getToken() completed but was canceled');\n }\n } catch (error) {\n this.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (this.repoInfo_.nodeAdmin) {\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_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 onAppCheckRevoked_(statusCode: string, explanation: string) {\n log('App check token revoked: ' + statusCode + '/' + explanation);\n this.appCheckToken_ = null;\n this.forceTokenRefresh_ = true;\n // Note: We don't close the connection as the developer may not have\n // enforcement enabled. The backend closes connections with enforcements.\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.invalidAppCheckTokenCount_++;\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\n this.appCheckTokenProvider_.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 this.tryAppCheck();\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 for (let i = 0; i < this.outstandingGets_.length; i++) {\n if (this.outstandingGets_[i]) {\n this.sendGet_(i);\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 (isNodeSdk()) {\n if (this.repoInfo_.nodeAdmin) {\n clientName = 'admin_node';\n } else {\n clientName = 'node';\n }\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path } from '../util/Path';\n\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 * @returns Whether this is a leaf node.\n */\n isLeafNode(): boolean;\n\n /**\n * Gets the priority of the node.\n * @returns The priority of the node.\n */\n getPriority(): Node;\n\n /**\n * Returns a duplicate node with the new priority.\n * @param newPriorityNode - New priority to set for the node.\n * @returns 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 childName - The name of the child to retrieve.\n * @returns 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 - The path of the child to retrieve.\n * @returns 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 childName - The name of the child to find the predecessor of.\n * @param childNode - The node to find the predecessor of.\n * @param index - The index to use to determine the predecessor\n * @returns 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 childName - The name of the child to update.\n * @param newChildNode - The new child node\n * @returns 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 - The path of the child to update.\n * @param newChildNode - The new child node, which may be an empty node\n * @returns The updated node.\n */\n updateChild(path: Path, newChildNode: Node): Node;\n\n /**\n * True if the immediate child specified exists\n */\n hasChild(childName: string): boolean;\n\n /**\n * @returns True if this node has no value or children.\n */\n isEmpty(): boolean;\n\n /**\n * @returns The number of children of this node.\n */\n numChildren(): number;\n\n /**\n * Calls action for each child.\n * @param action - Action to be called for\n * each child. It's passed the child name and the child node.\n * @returns 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 * @returns Value of this node as JSON.\n */\n val(exportFormat?: boolean): unknown;\n\n /**\n * @returns hash representing the node contents.\n */\n hash(): string;\n\n /**\n * @param other - Another node\n * @returns -1 for less than, 0 for equal, 1 for greater than other\n */\n compareTo(other: Node): number;\n\n /**\n * @returns Whether or not this snapshot equals other\n */\n equals(other: Node): boolean;\n\n /**\n * @returns This node, with the specified index now available\n */\n withIndex(indexDefinition: Index): Node;\n\n isIndexed(indexDefinition: Index): boolean;\n}\n\nexport class NamedNode {\n constructor(public name: string, public node: Node) {}\n\n static Wrap(name: string, node: Node) {\n return new NamedNode(name, node);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Comparator } from '../../util/SortedMap';\nimport { MIN_NAME } from '../../util/util';\nimport { Node, NamedNode } from '../Node';\n\nexport abstract class Index {\n abstract compare(a: NamedNode, b: NamedNode): number;\n\n abstract isDefinedOn(node: Node): boolean;\n\n /**\n * @returns 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 *\n * @returns 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 * @returns 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 * @returns 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 abstract makePost(indexValue: unknown, name: string): NamedNode;\n\n /**\n * @returns String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { ChildrenNode } from '../ChildrenNode';\nimport { Node, NamedNode } from '../Node';\n\nimport { Index } from './Index';\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 compare(a: NamedNode, b: NamedNode): number {\n return nameCompare(a.name, b.name);\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 indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return false; // The key for a node never changes.\n }\n minPost() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\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 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 * @returns 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 nodeStack_: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>> = [];\n\n /**\n * @param node - Node to iterate.\n * @param isReverse_ - Whether or not to iterate in reverse\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 * @param key - Key associated with this node.\n * @param value - Value associated with this node.\n * @param color - Whether this node is red.\n * @param left - Left child.\n * @param 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 key - New key for the node, or null.\n * @param value - New value for the node, or null.\n * @param color - New color for the node, or null.\n * @param left - New left child for the node, or null.\n * @param right - New right child for the node, or null.\n * @returns 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 * @returns 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 * @returns 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 action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns 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 action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns 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 * @returns The minimum node in the tree.\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 * @returns The maximum key in the tree.\n */\n minKey(): K {\n return this.min_().key;\n }\n\n /**\n * @returns 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 * @param key - Key to insert.\n * @param value - Value to insert.\n * @param comparator - Comparator.\n * @returns 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 * @returns 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 key - The key of the item to remove.\n * @param comparator - Comparator.\n * @returns 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 * @returns Whether this is a RED node.\n */\n isRed_(): boolean {\n return this.color;\n }\n\n /**\n * @returns 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 * @returns 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 * @returns 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 * @returns 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 * @returns 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 * @returns Newt ree, 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 * @returns 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 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 * @returns 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 key - Key to be added.\n * @param value - Value to be added.\n * @param comparator - Comparator.\n * @returns 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 key - The key to remove.\n * @param comparator - Comparator.\n * @returns New tree, with item removed.\n */\n remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n return this;\n }\n\n /**\n * @returns The total number of nodes in the tree.\n */\n count(): number {\n return 0;\n }\n\n /**\n * @returns 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 action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns 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 action - Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @returns True if traversal was aborted.\n */\n reverseTraversal(action: (k: K, v: V) => void): boolean {\n return false;\n }\n\n minKey(): null {\n return null;\n }\n\n maxKey(): null {\n return null;\n }\n\n check_(): number {\n return 0;\n }\n\n /**\n * @returns 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 */\n static EMPTY_NODE = new LLRBEmptyNode();\n\n /**\n * @param comparator_ - Key comparator.\n * @param 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 key - Key to be added.\n * @param value - Value to be added.\n * @returns 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 key - The key to remove.\n * @returns 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 key - The key to look up.\n * @returns 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 key - The key to find the predecessor of\n * @returns 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 * @returns True if the map is empty.\n */\n isEmpty(): boolean {\n return this.root_.isEmpty();\n }\n\n /**\n * @returns The total number of nodes in the map.\n */\n count(): number {\n return this.root_.count();\n }\n\n /**\n * @returns The minimum key in the map.\n */\n minKey(): K | null {\n return this.root_.minKey();\n }\n\n /**\n * @returns 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 action - Callback function to be called\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 */\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 action - Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @returns 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 * @returns 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../util/util';\n\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport {\n Path,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\nimport { doubleToIEEE754String, sha1 } from '../util/util';\n\nimport { ChildrenNodeConstructor } from './ChildrenNode';\nimport { Index } from './indexes/Index';\nimport { Node } from './Node';\nimport { priorityHashText, validatePriorityNode } from './snap';\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 */\n static VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n private lazyHash_: string | null = null;\n\n /**\n * @param value_ - The value to store in this leaf node. The object type is\n * possible in the event of a deferred value\n * @param 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 (pathIsEmpty(path)) {\n return this;\n } else if (pathGetFront(path) === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\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 = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n } else {\n assert(\n front !== '.priority' || pathGetLength(path) === 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 pathPopFront(path),\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 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 * @returns The value of the node.\n */\n getValue(): Indexable | string | number | boolean {\n return this.value_;\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 */\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 withIndex(): Node {\n return this;\n }\n isIndexed(): boolean {\n return true;\n }\n equals(other: Node): boolean {\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLRBNode, SortedMap } from '../util/SortedMap';\n\nimport { NamedNode } from './Node';\n\nconst LOG_2 = Math.log(2);\n\nclass Base12Num {\n count: number;\n private current_: number;\n private bits_: number;\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 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 * @param childList - Unsorted list of children\n * @param cmp - The comparison method to be used\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, contains, map, safeGet } from '@firebase/util';\n\nimport { SortedMap } from '../util/SortedMap';\n\nimport { buildChildSet } from './childSet';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX } from './indexes/KeyIndex';\nimport { PRIORITY_INDEX } from './indexes/PriorityIndex';\nimport { NamedNode, Node } from './Node';\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathGetLength, pathPopFront } from '../util/Path';\nimport { SortedMap, SortedMapIterator } from '../util/SortedMap';\nimport { MAX_NAME, MIN_NAME, sha1 } from '../util/util';\n\nimport { NAME_COMPARATOR } from './comparators';\nimport { Index } from './indexes/Index';\nimport { KEY_INDEX, KeyIndex } from './indexes/KeyIndex';\nimport {\n PRIORITY_INDEX,\n setMaxNode as setPriorityMaxNode\n} from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\nimport { priorityHashText, setMaxNode, validatePriorityNode } from './snap';\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 */\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 * @param children_ - List of children of this node..\n * @param priorityNode_ - The priority of this node (as a snapshot node).\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 = pathGetFront(path);\n if (front === null) {\n return this;\n }\n\n return this.getImmediateChild(front).getChild(pathPopFront(path));\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 = pathGetFront(path);\n if (front === null) {\n return newChildNode;\n } else {\n assert(\n pathGetFront(path) !== '.priority' || pathGetLength(path) === 1,\n '.priority must be the last token in a path'\n );\n const newImmediateChild = this.getImmediateChild(front).updateChild(\n pathPopFront(path),\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 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 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 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 */\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 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 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 getIterator(\n indexDefinition: Index\n ): SortedMapIterator<string | NamedNode, Node, NamedNode> {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\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 getReverseIterator(\n indexDefinition: Index\n ): SortedMapIterator<string | NamedNode, Node, NamedNode> {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\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 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 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 isIndexed(index: Index): boolean {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\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 */\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\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 */\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, assert } from '@firebase/util';\n\nimport { Indexable } from '../util/misc';\nimport { SortedMap } from '../util/SortedMap';\nimport { each } from '../util/util';\n\nimport { ChildrenNode } from './ChildrenNode';\nimport { buildChildSet } from './childSet';\nimport { NAME_COMPARATOR, NAME_ONLY_COMPARATOR } from './comparators';\nimport { PRIORITY_INDEX, setNodeFromJSON } from './indexes/PriorityIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\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 priority - Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Path, pathGetFront, pathIsEmpty, pathSlice } from '../../util/Path';\nimport { MAX_NAME, nameCompare } from '../../util/util';\nimport { ChildrenNode, MAX_NODE } from '../ChildrenNode';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class PathIndex extends Index {\n constructor(private indexPath_: Path) {\n super();\n\n assert(\n !pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority',\n \"Can't create PathIndex with empty path or .priority key\"\n );\n }\n\n protected extractChild(snap: Node): Node {\n return snap.getChild(this.indexPath_);\n }\n isDefinedOn(node: Node): boolean {\n return !node.getChild(this.indexPath_).isEmpty();\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 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 maxPost(): NamedNode {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n toString(): string {\n return pathSlice(this.indexPath_, 0).join('/');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameCompare } from '../../util/util';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\nimport { Index } from './Index';\n\nexport class ValueIndex extends Index {\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 isDefinedOn(node: Node): boolean {\n return true;\n }\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.equals(newNode);\n }\n minPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n maxPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MAX;\n }\n\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n\n /**\n * @returns 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nexport const enum ChangeType {\n /** Event type for a child added */\n CHILD_ADDED = 'child_added',\n /** Event type for a child removed */\n CHILD_REMOVED = 'child_removed',\n /** Event type for a child changed */\n CHILD_CHANGED = 'child_changed',\n /** Event type for a child moved */\n CHILD_MOVED = 'child_moved',\n /** Event type for a value change */\n VALUE = 'value'\n}\n\nexport interface Change {\n /** @param type - The event type */\n type: ChangeType;\n /** @param snapshotNode - The data */\n snapshotNode: Node;\n /** @param childName - The name for this child, if it's a child even */\n childName?: string;\n /** @param oldSnap - Used for intermediate processing of child changed events */\n oldSnap?: Node;\n /** * @param prevName - The name for the previous child, if applicable */\n prevName?: string | null;\n}\n\nexport function changeValue(snapshotNode: Node): Change {\n return { type: ChangeType.VALUE, snapshotNode };\n}\n\nexport function changeChildAdded(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_ADDED, snapshotNode, childName };\n}\n\nexport function changeChildRemoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_REMOVED, snapshotNode, childName };\n}\n\nexport function changeChildChanged(\n childName: string,\n snapshotNode: Node,\n oldSnap: Node\n): Change {\n return {\n type: ChangeType.CHILD_CHANGED,\n snapshotNode,\n childName,\n oldSnap\n };\n}\n\nexport function changeChildMoved(\n childName: string,\n snapshotNode: Node\n): Change {\n return { type: ChangeType.CHILD_MOVED, snapshotNode, childName };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\n\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\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 changeChildRemoved(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(changeChildAdded(key, newChild));\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildChanged(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 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 changeChildRemoved(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 changeChildChanged(key, childNode, oldChild)\n );\n }\n } else {\n optChangeAccumulator.trackChildChange(\n changeChildAdded(key, childNode)\n );\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\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 filtersNodes(): boolean {\n return false;\n }\n getIndexedFilter(): IndexedFilter {\n return this;\n }\n getIndex(): Index {\n return this.index_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NamedNode, Node } from '../../../core/snap/Node';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { Path } from '../../util/Path';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\n\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n */\nexport class RangedFilter implements NodeFilter {\n private indexedFilter_: IndexedFilter;\n\n private index_: Index;\n\n private startPost_: NamedNode;\n\n private endPost_: NamedNode;\n\n private startIsInclusive_: boolean;\n\n private endIsInclusive_: boolean;\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 this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\n }\n\n getStartPost(): NamedNode {\n return this.startPost_;\n }\n\n getEndPost(): NamedNode {\n return this.endPost_;\n }\n\n matches(node: NamedNode): boolean {\n const isWithinStart = this.startIsInclusive_\n ? this.index_.compare(this.getStartPost(), node) <= 0\n : this.index_.compare(this.getStartPost(), node) < 0;\n const isWithinEnd = this.endIsInclusive_\n ? this.index_.compare(node, this.getEndPost()) <= 0\n : this.index_.compare(node, this.getEndPost()) < 0;\n return isWithinStart && isWithinEnd;\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 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 updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.indexedFilter_;\n }\n getIndex(): Index {\n return this.index_;\n }\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 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Index } from '../../snap/indexes/Index';\nimport { NamedNode, Node } from '../../snap/Node';\nimport { Path } from '../../util/Path';\nimport {\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from '../Change';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { QueryParams } from '../QueryParams';\n\nimport { IndexedFilter } from './IndexedFilter';\nimport { NodeFilter } from './NodeFilter';\nimport { RangedFilter } from './RangedFilter';\n\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n */\nexport class LimitedFilter implements NodeFilter {\n private readonly rangedFilter_: RangedFilter;\n\n private readonly index_: Index;\n\n private readonly limit_: number;\n\n private readonly reverse_: boolean;\n\n private readonly startIsInclusive_: boolean;\n\n private readonly endIsInclusive_: boolean;\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 this.startIsInclusive_ = !params.startAfterSet_;\n this.endIsInclusive_ = !params.endBeforeSet_;\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 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 if (!this.withinDirectionalStart(next)) {\n // if we have not reached the start, skip to the next element\n continue;\n } else if (!this.withinDirectionalEnd(next)) {\n // if we have reached the end, stop adding elements\n break;\n } else {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\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\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n } else {\n iterator = filtered.getIterator(this.index_);\n }\n\n let count = 0;\n while (iterator.hasNext()) {\n const next = iterator.getNext();\n const inRange =\n count < this.limit_ &&\n this.withinDirectionalStart(next) &&\n this.withinDirectionalEnd(next);\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 updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n filtersNodes(): boolean {\n return true;\n }\n getIndexedFilter(): IndexedFilter {\n return this.rangedFilter_.getIndexedFilter();\n }\n getIndex(): Index {\n return this.index_;\n }\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 changeChildChanged(childKey, childSnap, oldChildSnap)\n );\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n changeChildRemoved(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 changeChildAdded(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 changeChildRemoved(windowBoundary.name, windowBoundary.node)\n );\n changeAccumulator.trackChildChange(\n changeChildAdded(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 private withinDirectionalStart = (node: NamedNode) =>\n this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\n\n private withinDirectionalEnd = (node: NamedNode) =>\n this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\n\n private withinStartPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n this.rangedFilter_.getStartPost(),\n node\n );\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n\n private withinEndPost = (node: NamedNode) => {\n const compareRes = this.index_.compare(\n node,\n this.rangedFilter_.getEndPost()\n );\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, stringify } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { PathIndex } from '../snap/indexes/PathIndex';\nimport { PRIORITY_INDEX, PriorityIndex } from '../snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../snap/indexes/ValueIndex';\nimport { MAX_NAME, MIN_NAME } from '../util/util';\n\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { LimitedFilter } from './filter/LimitedFilter';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { RangedFilter } from './filter/RangedFilter';\n\n/**\n * Wire Protocol Constants\n */\nconst enum WIRE_PROTOCOL_CONSTANTS {\n INDEX_START_VALUE = 'sp',\n INDEX_START_NAME = 'sn',\n INDEX_START_IS_INCLUSIVE = 'sin',\n INDEX_END_VALUE = 'ep',\n INDEX_END_NAME = 'en',\n INDEX_END_IS_INCLUSIVE = 'ein',\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 */\nconst enum REST_QUERY_CONSTANTS {\n ORDER_BY = 'orderBy',\n PRIORITY_INDEX = '$priority',\n VALUE_INDEX = '$value',\n KEY_INDEX = '$key',\n START_AFTER = 'startAfter',\n START_AT = 'startAt',\n END_AT = 'endAt',\n END_BEFORE = 'endBefore',\n LIMIT_TO_FIRST = 'limitToFirst',\n LIMIT_TO_LAST = 'limitToLast'\n}\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 *\n * @internal\n */\nexport class QueryParams {\n limitSet_ = false;\n startSet_ = false;\n startNameSet_ = false;\n startAfterSet_ = false; // can only be true if startSet_ is true\n endSet_ = false;\n endNameSet_ = false;\n endBeforeSet_ = false; // can only be true if endSet_ is true\n limit_ = 0;\n viewFrom_ = '';\n indexStartValue_: unknown | null = null;\n indexStartName_ = '';\n indexEndValue_: unknown | null = null;\n indexEndName_ = '';\n index_: PriorityIndex = PRIORITY_INDEX;\n\n hasStart(): boolean {\n return this.startSet_;\n }\n\n /**\n * @returns 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 this.viewFrom_ === WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n }\n\n /**\n * Only valid to call if hasStart() returns true\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 */\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 hasEnd(): boolean {\n return this.endSet_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\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 */\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 hasLimit(): boolean {\n return this.limitSet_;\n }\n\n /**\n * @returns 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 */\n getLimit(): number {\n assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n\n getIndex(): Index {\n return this.index_;\n }\n\n loadsAllData(): boolean {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n\n isDefault(): boolean {\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\n }\n\n copy(): QueryParams {\n const copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.startAfterSet_ = this.startAfterSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.endBeforeSet_ = this.endBeforeSet_;\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\nexport function queryParamsGetNodeFilter(queryParams: QueryParams): NodeFilter {\n if (queryParams.loadsAllData()) {\n return new IndexedFilter(queryParams.getIndex());\n } else if (queryParams.hasLimit()) {\n return new LimitedFilter(queryParams);\n } else {\n return new RangedFilter(queryParams);\n }\n}\n\nexport function queryParamsLimit(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n}\n\nexport function queryParamsLimitToFirst(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n return newParams;\n}\n\nexport function queryParamsLimitToLast(\n queryParams: QueryParams,\n newLimit: number\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n return newParams;\n}\n\nexport function queryParamsStartAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.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\nexport function queryParamsStartAfter(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsStartAt(queryParams, indexValue, key);\n } else {\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\n }\n params.startAfterSet_ = true;\n return params;\n}\n\nexport function queryParamsEndAt(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n const newParams = queryParams.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\nexport function queryParamsEndBefore(\n queryParams: QueryParams,\n indexValue: unknown,\n key?: string | null\n): QueryParams {\n let params: QueryParams;\n if (queryParams.index_ === KEY_INDEX || !!key) {\n params = queryParamsEndAt(queryParams, indexValue, key);\n } else {\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\n }\n params.endBeforeSet_ = true;\n return params;\n}\n\nexport function queryParamsOrderBy(\n queryParams: QueryParams,\n index: Index\n): QueryParams {\n const newParams = queryParams.copy();\n newParams.index_ = index;\n return newParams;\n}\n\n/**\n * Returns a set of REST query string parameters representing this query.\n *\n * @returns query string parameters\n */\nexport function queryParamsToRestQueryStringParameters(\n queryParams: QueryParams\n): Record<string, string | number> {\n const qs: Record<string, string | number> = {};\n\n if (queryParams.isDefault()) {\n return qs;\n }\n\n let orderBy;\n if (queryParams.index_ === PRIORITY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.PRIORITY_INDEX;\n } else if (queryParams.index_ === VALUE_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.VALUE_INDEX;\n } else if (queryParams.index_ === KEY_INDEX) {\n orderBy = REST_QUERY_CONSTANTS.KEY_INDEX;\n } else {\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = queryParams.index_.toString();\n }\n qs[REST_QUERY_CONSTANTS.ORDER_BY] = stringify(orderBy);\n\n if (queryParams.startSet_) {\n const startParam = queryParams.startAfterSet_\n ? REST_QUERY_CONSTANTS.START_AFTER\n : REST_QUERY_CONSTANTS.START_AT;\n qs[startParam] = stringify(queryParams.indexStartValue_);\n if (queryParams.startNameSet_) {\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\n }\n }\n\n if (queryParams.endSet_) {\n const endParam = queryParams.endBeforeSet_\n ? REST_QUERY_CONSTANTS.END_BEFORE\n : REST_QUERY_CONSTANTS.END_AT;\n qs[endParam] = stringify(queryParams.indexEndValue_);\n if (queryParams.endNameSet_) {\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\n }\n }\n\n if (queryParams.limitSet_) {\n if (queryParams.isViewFromLeft()) {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_FIRST] = queryParams.limit_;\n } else {\n qs[REST_QUERY_CONSTANTS.LIMIT_TO_LAST] = queryParams.limit_;\n }\n }\n\n return qs;\n}\n\nexport function queryParamsGetQueryObject(\n queryParams: QueryParams\n): Record<string, unknown> {\n const obj: Record<string, unknown> = {};\n if (queryParams.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] =\n queryParams.indexStartValue_;\n if (queryParams.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] =\n queryParams.indexStartName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE] =\n !queryParams.startAfterSet_;\n }\n if (queryParams.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = queryParams.indexEndValue_;\n if (queryParams.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = queryParams.indexEndName_;\n }\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE] =\n !queryParams.endBeforeSet_;\n }\n if (queryParams.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = queryParams.limit_;\n let viewFrom = queryParams.viewFrom_;\n if (viewFrom === '') {\n if (queryParams.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 (queryParams.index_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = queryParams.index_.toString();\n }\n return obj;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n jsonEval,\n safeGet,\n querystring,\n Deferred\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { logWrapper, warn } from './util/util';\nimport { QueryContext } from './view/EventRegistration';\nimport { queryParamsToRestQueryStringParameters } from './view/QueryParams';\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 listens_: { [k: string]: object } = {};\n\n static getListenId_(query: QueryContext, tag?: number | null): string {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n assert(\n query._queryParams.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_ - 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 authTokenProvider_: AuthTokenProvider,\n private appCheckTokenProvider_: AppCheckTokenProvider\n ) {\n super();\n }\n\n /** @inheritDoc */\n listen(\n query: QueryContext,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: unknown) => void\n ) {\n const pathString = query._path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\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 = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\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: QueryContext, tag: number | null) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n\n get(query: QueryContext): Promise<string> {\n const queryStringParameters = queryParamsToRestQueryStringParameters(\n query._queryParams\n );\n\n const pathString = query._path.toString();\n\n const deferred = new Deferred<string>();\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_(\n pathString,\n data,\n /*isMerge=*/ false,\n /*tag=*/ null\n );\n deferred.resolve(data as string);\n } else {\n deferred.reject(new Error(data as string));\n }\n }\n );\n return deferred.promise;\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 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 return Promise.all([\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\n ]).then(([authToken, appCheckToken]) => {\n if (authToken && authToken.accessToken) {\n queryStringParameters['auth'] = authToken.accessToken;\n }\n if (appCheckToken && appCheckToken.token) {\n queryStringParameters['ac'] = appCheckToken.token;\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\n\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { Node } from './snap/Node';\nimport { Path, pathGetFront, pathIsEmpty, pathPopFront } from './util/Path';\n\n/**\n * Helper class to store a sparse set of snapshots.\n */\nexport interface SparseSnapshotTree {\n value: Node | null;\n readonly children: Map<string, SparseSnapshotTree>;\n}\n\nexport function newSparseSnapshotTree(): SparseSnapshotTree {\n return {\n value: null,\n children: new Map()\n };\n}\n\n/**\n * Gets the node stored at the given path if one exists.\n * Only seems to be used in tests.\n *\n * @param path - Path to look up snapshot for.\n * @returns The retrieved node, or null.\n */\nexport function sparseSnapshotTreeFind(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): Node | null {\n if (sparseSnapshotTree.value != null) {\n return sparseSnapshotTree.value.getChild(path);\n } else if (!pathIsEmpty(path) && sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const childTree = sparseSnapshotTree.children.get(childKey);\n return sparseSnapshotTreeFind(childTree, 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 */\nexport function sparseSnapshotTreeRemember(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path,\n data: Node\n): void {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = data;\n sparseSnapshotTree.children.clear();\n } else if (sparseSnapshotTree.value !== null) {\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\n } else {\n const childKey = pathGetFront(path);\n if (!sparseSnapshotTree.children.has(childKey)) {\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\n }\n\n const child = sparseSnapshotTree.children.get(childKey);\n path = pathPopFront(path);\n sparseSnapshotTreeRemember(child, 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 * @returns True if this node should now be removed.\n */\nexport function sparseSnapshotTreeForget(\n sparseSnapshotTree: SparseSnapshotTree,\n path: Path\n): boolean {\n if (pathIsEmpty(path)) {\n sparseSnapshotTree.value = null;\n sparseSnapshotTree.children.clear();\n return true;\n } else {\n if (sparseSnapshotTree.value !== null) {\n if (sparseSnapshotTree.value.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n } else {\n const value = sparseSnapshotTree.value;\n sparseSnapshotTree.value = null;\n\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\n });\n\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\n }\n } else if (sparseSnapshotTree.children.size > 0) {\n const childKey = pathGetFront(path);\n path = pathPopFront(path);\n if (sparseSnapshotTree.children.has(childKey)) {\n const safeToRemove = sparseSnapshotTreeForget(\n sparseSnapshotTree.children.get(childKey),\n path\n );\n if (safeToRemove) {\n sparseSnapshotTree.children.delete(childKey);\n }\n }\n\n return sparseSnapshotTree.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 */\nexport function sparseSnapshotTreeForEachTree(\n sparseSnapshotTree: SparseSnapshotTree,\n prefixPath: Path,\n func: (a: Path, b: Node) => unknown\n): void {\n if (sparseSnapshotTree.value !== null) {\n func(prefixPath, sparseSnapshotTree.value);\n } else {\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n sparseSnapshotTreeForEachTree(tree, path, func);\n });\n }\n}\n\n/**\n * Iterates through each immediate child and triggers the callback.\n * Only seems to be used in tests.\n *\n * @param func - The function to invoke for each child.\n */\nexport function sparseSnapshotTreeForEachChild(\n sparseSnapshotTree: SparseSnapshotTree,\n func: (a: string, b: SparseSnapshotTree) => void\n): void {\n sparseSnapshotTree.children.forEach((tree, key) => {\n func(key, tree);\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\n\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ - The collection to \"listen\" to.\n */\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains } from '@firebase/util';\n\nimport { ServerActions } from '../ServerActions';\nimport { setTimeoutNonBlocking, each } from '../util/util';\n\nimport { StatsCollection } from './StatsCollection';\nimport { StatsListener } from './StatsListener';\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\nexport class StatsReporter {\n private statsListener_: StatsListener;\n statsToReport_: { [k: string]: boolean } = {};\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 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\nexport function statsReporterIncludeStat(\n reporter: StatsReporter,\n stat: string\n) {\n reporter.statsToReport_[stat] = true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { newOperationSourceUser, Operation, OperationType } from './Operation';\n\nexport class AckUserWrite implements Operation {\n /** @inheritDoc */\n type = OperationType.ACK_USER_WRITE;\n\n /** @inheritDoc */\n source = newOperationSourceUser();\n\n /**\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\n */\n constructor(\n /** @inheritDoc */ public path: Path,\n /** @inheritDoc */ public affectedTree: ImmutableTree<boolean>,\n /** @inheritDoc */ public revert: boolean\n ) {}\n operationForChild(childName: string): AckUserWrite {\n if (!pathIsEmpty(this.path)) {\n assert(\n pathGetFront(this.path) === childName,\n 'operationForChild called for unrelated child.'\n );\n return new AckUserWrite(\n pathPopFront(this.path),\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(newEmptyPath(), childTree, this.revert);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './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 (pathIsEmpty(this.path)) {\n return new ListenComplete(this.source, newEmptyPath());\n } else {\n return new ListenComplete(this.source, pathPopFront(this.path));\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { newEmptyPath, Path, pathIsEmpty, pathPopFront } from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './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 (pathIsEmpty(this.path)) {\n return new Overwrite(\n this.source,\n newEmptyPath(),\n this.snap.getImmediateChild(childName)\n );\n } else {\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from '../util/Path';\n\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Overwrite } from './Overwrite';\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 operationForChild(childName: string): Operation {\n if (pathIsEmpty(this.path)) {\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, newEmptyPath(), childTree.value);\n } else {\n // This is a merge at a deeper level\n return new Merge(this.source, newEmptyPath(), childTree);\n }\n } else {\n assert(\n pathGetFront(this.path) === childName,\n \"Can't get a merge for a child not on the path of the operation\"\n );\n return new Merge(this.source, pathPopFront(this.path), this.children);\n }\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } 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 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 */\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 */\n isFiltered(): boolean {\n return this.filtered_;\n }\n\n isCompleteForPath(path: Path): boolean {\n if (pathIsEmpty(path)) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n\n const childKey = pathGetFront(path);\n return this.isCompleteForChild(childKey);\n }\n\n isCompleteForChild(key: string): boolean {\n return (\n (this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)\n );\n }\n\n getNode(): Node {\n return this.node_;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertionError } from '@firebase/util';\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\n\nimport { Change, ChangeType, changeChildMoved } from './Change';\nimport { Event } from './Event';\nimport { EventRegistration, QueryContext } from './EventRegistration';\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 */\nexport class EventGenerator {\n index_: Index;\n\n constructor(public query_: QueryContext) {\n this.index_ = this.query_._queryParams.getIndex();\n }\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 */\nexport function eventGeneratorGenerateEventsForChanges(\n eventGenerator: EventGenerator,\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 === ChangeType.CHILD_CHANGED &&\n eventGenerator.index_.indexedValueChanged(\n change.oldSnap as Node,\n change.snapshotNode\n )\n ) {\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\n }\n });\n\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_REMOVED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_ADDED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_MOVED,\n moves,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.CHILD_CHANGED,\n changes,\n eventRegistrations,\n eventCache\n );\n eventGeneratorGenerateEventsForType(\n eventGenerator,\n events,\n ChangeType.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 */\nfunction eventGeneratorGenerateEventsForType(\n eventGenerator: EventGenerator,\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((a, b) =>\n eventGeneratorCompareChanges(eventGenerator, a, b)\n );\n filteredChanges.forEach(change => {\n const materializedChange = eventGeneratorMaterializeSingleChange(\n eventGenerator,\n change,\n eventCache\n );\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(\n registration.createEvent(materializedChange, eventGenerator.query_)\n );\n }\n });\n });\n}\n\nfunction eventGeneratorMaterializeSingleChange(\n eventGenerator: EventGenerator,\n change: Change,\n eventCache: Node\n): Change {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n } else {\n change.prevName = eventCache.getPredecessorChildName(\n change.childName,\n change.snapshotNode,\n eventGenerator.index_\n );\n return change;\n }\n}\n\nfunction eventGeneratorCompareChanges(\n eventGenerator: EventGenerator,\n a: Change,\n b: Change\n) {\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 eventGenerator.index_.compare(aWrapped, bWrapped);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Node } from '../snap/Node';\n\nimport { CacheNode } from './CacheNode';\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 */\nexport interface ViewCache {\n readonly eventCache: CacheNode;\n readonly serverCache: CacheNode;\n}\n\nexport function newViewCache(\n eventCache: CacheNode,\n serverCache: CacheNode\n): ViewCache {\n return { eventCache, serverCache };\n}\n\nexport function viewCacheUpdateEventSnap(\n viewCache: ViewCache,\n eventSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n new CacheNode(eventSnap, complete, filtered),\n viewCache.serverCache\n );\n}\n\nexport function viewCacheUpdateServerSnap(\n viewCache: ViewCache,\n serverSnap: Node,\n complete: boolean,\n filtered: boolean\n): ViewCache {\n return newViewCache(\n viewCache.eventCache,\n new CacheNode(serverSnap, complete, filtered)\n );\n}\n\nexport function viewCacheGetCompleteEventSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.eventCache.isFullyInitialized()\n ? viewCache.eventCache.getNode()\n : null;\n}\n\nexport function viewCacheGetCompleteServerSnap(\n viewCache: ViewCache\n): Node | null {\n return viewCache.serverCache.isFullyInitialized()\n ? viewCache.serverCache.getNode()\n : null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './Path';\nimport { SortedMap } from './SortedMap';\nimport { each, stringCompare } from './util';\n\nlet emptyChildrenSingleton: SortedMap<string, ImmutableTree<null>>;\n\n/**\n * Singleton empty children collection.\n *\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 static fromObject<T>(obj: { [k: string]: T }): ImmutableTree<T> {\n let tree: ImmutableTree<T> = new ImmutableTree<T>(null);\n each(obj, (childPath: string, childSnap: T) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\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 */\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:}`\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param relativePath - The remainder of the path\n * @param predicate - The predicate to satisfy to return a node\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: newEmptyPath(), value: this.value };\n } else {\n if (pathIsEmpty(relativePath)) {\n return null;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue =\n child.findRootMostMatchingPathAndValue(\n pathPopFront(relativePath),\n predicate\n );\n if (childExistingPathAndValue != null) {\n const fullPath = pathChild(\n new Path(front),\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 */\n findRootMostValueAndPath(\n relativePath: Path\n ): { path: Path; value: T } | null {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n\n /**\n * @returns The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree<T> {\n if (pathIsEmpty(relativePath)) {\n return this;\n } else {\n const front = pathGetFront(relativePath);\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(pathPopFront(relativePath));\n } else {\n return new ImmutableTree<T>(null);\n }\n }\n }\n\n /**\n * Sets a value at the specified path.\n *\n * @param relativePath - Path to set value at.\n * @param toSet - Value to set.\n * @returns Resulting tree.\n */\n set(relativePath: Path, toSet: T | null): ImmutableTree<T> {\n if (pathIsEmpty(relativePath)) {\n return new ImmutableTree(toSet, this.children);\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree<T>(null);\n const newChild = child.set(pathPopFront(relativePath), 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 relativePath - Path to value to remove.\n * @returns Resulting tree.\n */\n remove(relativePath: Path): ImmutableTree<T> {\n if (pathIsEmpty(relativePath)) {\n if (this.children.isEmpty()) {\n return new ImmutableTree<T>(null);\n } else {\n return new ImmutableTree(null, this.children);\n }\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(pathPopFront(relativePath));\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 new ImmutableTree<T>(null);\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 relativePath - Path to get value for.\n * @returns Value at path, or null.\n */\n get(relativePath: Path): T | null {\n if (pathIsEmpty(relativePath)) {\n return this.value;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front);\n if (child) {\n return child.get(pathPopFront(relativePath));\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 relativePath - Path to replace subtree for.\n * @param newTree - New tree.\n * @returns Resulting tree.\n */\n setTree(relativePath: Path, newTree: ImmutableTree<T>): ImmutableTree<T> {\n if (pathIsEmpty(relativePath)) {\n return newTree;\n } else {\n const front = pathGetFront(relativePath);\n const child = this.children.get(front) || new ImmutableTree<T>(null);\n const newChild = child.setTree(pathPopFront(relativePath), 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 */\n fold<V>(fn: (path: Path, value: T, children: { [k: string]: V }) => V): V {\n return this.fold_(newEmptyPath(), fn);\n }\n\n /**\n * Recursive helper for public-facing fold() method\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_(pathChild(pathSoFar, 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 */\n findOnPath<V>(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, newEmptyPath(), 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 (pathIsEmpty(pathToFollow)) {\n return null;\n } else {\n const front = pathGetFront(pathToFollow)!;\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(\n pathPopFront(pathToFollow),\n pathChild(pathSoFar, front),\n f\n );\n } else {\n return null;\n }\n }\n }\n }\n\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree<T> {\n return this.foreachOnPath_(path, newEmptyPath(), f);\n }\n\n private foreachOnPath_(\n pathToFollow: Path,\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree<T> {\n if (pathIsEmpty(pathToFollow)) {\n return this;\n } else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathGetFront(pathToFollow);\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(\n pathPopFront(pathToFollow),\n pathChild(currentRelativePath, front),\n f\n );\n } else {\n return new ImmutableTree<T>(null);\n }\n }\n }\n\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param f - A function to be called with the path from the root of the tree to\n * a node, and the value at that node. Called in depth-first order.\n */\n foreach(f: (path: Path, value: T) => void) {\n this.foreach_(newEmptyPath(), 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_(pathChild(currentRelativePath, childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n }\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathIsEmpty\n} from './util/Path';\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(public writeTree_: ImmutableTree<Node>) {}\n\n static empty(): CompoundWrite {\n return new CompoundWrite(new ImmutableTree(null));\n }\n}\n\nexport function compoundWriteAddWrite(\n compoundWrite: CompoundWrite,\n path: Path,\n node: Node\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return new CompoundWrite(new ImmutableTree(node));\n } else {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = newRelativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(\n compoundWrite.writeTree_.set(rootMostPath, value)\n );\n } else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n}\n\nexport function compoundWriteAddWrites(\n compoundWrite: CompoundWrite,\n path: Path,\n updates: { [name: string]: Node }\n): CompoundWrite {\n let newWrite = compoundWrite;\n each(updates, (childKey: string, node: Node) => {\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, 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 compoundWrite - The CompoundWrite to remove.\n * @param path - The path at which a write and all deeper writes should be removed\n * @returns The new CompoundWrite with the removed path\n */\nexport function compoundWriteRemoveWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return CompoundWrite.empty();\n } else {\n const newWriteTree = compoundWrite.writeTree_.setTree(\n path,\n new ImmutableTree<Node>(null)\n );\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 compoundWrite - The CompoundWrite to check.\n * @param path - The path to check for\n * @returns Whether there is a complete write at that path\n */\nexport function compoundWriteHasCompleteWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): boolean {\n return compoundWriteGetCompleteNode(compoundWrite, 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 compoundWrite - The CompoundWrite to get the node from.\n * @param path - The path to get a complete write\n * @returns The node if complete at that path, or null otherwise.\n */\nexport function compoundWriteGetCompleteNode(\n compoundWrite: CompoundWrite,\n path: Path\n): Node | null {\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return compoundWrite.writeTree_\n .get(rootmost.path)\n .getChild(newRelativePath(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 * @param compoundWrite - The CompoundWrite to get children from.\n * @returns A list of all complete children.\n */\nexport function compoundWriteGetCompleteChildren(\n compoundWrite: CompoundWrite\n): NamedNode[] {\n const children: NamedNode[] = [];\n const node = compoundWrite.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 compoundWrite.writeTree_.children.inorderTraversal(\n (childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n }\n );\n }\n return children;\n}\n\nexport function compoundWriteChildCompoundWrite(\n compoundWrite: CompoundWrite,\n path: Path\n): CompoundWrite {\n if (pathIsEmpty(path)) {\n return compoundWrite;\n } else {\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n } else {\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\n }\n }\n}\n\n/**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @returns Whether this CompoundWrite is empty\n */\nexport function compoundWriteIsEmpty(compoundWrite: CompoundWrite): boolean {\n return compoundWrite.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 * @returns The node with all writes applied\n */\nexport function compoundWriteApply(\n compoundWrite: CompoundWrite,\n node: Node\n): Node {\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\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(\n pathChild(relativePath, childKey),\n childTree,\n node\n );\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(\n pathChild(relativePath, '.priority'),\n priorityWrite\n );\n }\n return node;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError, safeGet } from '@firebase/util';\n\nimport {\n CompoundWrite,\n compoundWriteAddWrite,\n compoundWriteAddWrites,\n compoundWriteApply,\n compoundWriteChildCompoundWrite,\n compoundWriteGetCompleteChildren,\n compoundWriteGetCompleteNode,\n compoundWriteHasCompleteWrite,\n compoundWriteIsEmpty,\n compoundWriteRemoveWrite\n} from './CompoundWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Index } from './snap/indexes/Index';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from './snap/Node';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathContains,\n pathGetFront,\n pathIsEmpty,\n pathPopFront\n} from './util/Path';\nimport { each } from './util/util';\nimport { CacheNode } from './view/CacheNode';\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 * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n */\nexport function writeTreeChildWrites(\n writeTree: WriteTree,\n path: Path\n): WriteTreeRef {\n return newWriteTreeRef(path, writeTree);\n}\n\n/**\n * Record a new overwrite from user code.\n *\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\n */\nexport function writeTreeAddOverwrite(\n writeTree: WriteTree,\n path: Path,\n snap: Node,\n writeId: number,\n visible?: boolean\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older write on top of newer ones'\n );\n if (visible === undefined) {\n visible = true;\n }\n writeTree.allWrites.push({\n path,\n snap,\n writeId,\n visible\n });\n\n if (visible) {\n writeTree.visibleWrites = compoundWriteAddWrite(\n writeTree.visibleWrites,\n path,\n snap\n );\n }\n writeTree.lastWriteId = writeId;\n}\n\n/**\n * Record a new merge from user code.\n */\nexport function writeTreeAddMerge(\n writeTree: WriteTree,\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n) {\n assert(\n writeId > writeTree.lastWriteId,\n 'Stacking an older merge on top of newer ones'\n );\n writeTree.allWrites.push({\n path,\n children: changedChildren,\n writeId,\n visible: true\n });\n\n writeTree.visibleWrites = compoundWriteAddWrites(\n writeTree.visibleWrites,\n path,\n changedChildren\n );\n writeTree.lastWriteId = writeId;\n}\n\nexport function writeTreeGetWrite(\n writeTree: WriteTree,\n writeId: number\n): WriteRecord | null {\n for (let i = 0; i < writeTree.allWrites.length; i++) {\n const record = writeTree.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 * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\nexport function writeTreeRemoveWrite(\n writeTree: WriteTree,\n writeId: number\n): 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 = writeTree.allWrites.findIndex(s => {\n return s.writeId === writeId;\n });\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = writeTree.allWrites[idx];\n writeTree.allWrites.splice(idx, 1);\n\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n\n let i = writeTree.allWrites.length - 1;\n\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = writeTree.allWrites[i];\n if (currentWrite.visible) {\n if (\n i >= idx &&\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)\n ) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n } else if (pathContains(writeToRemove.path, 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 writeTreeResetTree_(writeTree);\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 writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n writeToRemove.path\n );\n } else {\n const children = writeToRemove.children;\n each(children, (childName: string) => {\n writeTree.visibleWrites = compoundWriteRemoveWrite(\n writeTree.visibleWrites,\n pathChild(writeToRemove.path, childName)\n );\n });\n }\n return true;\n }\n}\n\nfunction writeTreeRecordContainsPath_(\n writeRecord: WriteRecord,\n path: Path\n): boolean {\n if (writeRecord.snap) {\n return pathContains(writeRecord.path, path);\n } else {\n for (const childName in writeRecord.children) {\n if (\n writeRecord.children.hasOwnProperty(childName) &&\n pathContains(pathChild(writeRecord.path, childName), 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 */\nfunction writeTreeResetTree_(writeTree: WriteTree) {\n writeTree.visibleWrites = writeTreeLayerTree_(\n writeTree.allWrites,\n writeTreeDefaultFilter_,\n newEmptyPath()\n );\n if (writeTree.allWrites.length > 0) {\n writeTree.lastWriteId =\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\n } else {\n writeTree.lastWriteId = -1;\n }\n}\n\n/**\n * The default filter used when constructing the tree. Keep everything that's visible.\n */\nfunction writeTreeDefaultFilter_(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 */\nfunction writeTreeLayerTree_(\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: Path;\n if (write.snap) {\n if (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n relativePath,\n write.snap\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\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 (pathContains(treeRoot, writePath)) {\n relativePath = newRelativePath(treeRoot, writePath);\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n relativePath,\n write.children\n );\n } else if (pathContains(writePath, treeRoot)) {\n relativePath = newRelativePath(writePath, treeRoot);\n if (pathIsEmpty(relativePath)) {\n compoundWrite = compoundWriteAddWrites(\n compoundWrite,\n newEmptyPath(),\n write.children\n );\n } else {\n const child = safeGet(write.children, pathGetFront(relativePath));\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(pathPopFront(relativePath));\n compoundWrite = compoundWriteAddWrite(\n compoundWrite,\n newEmptyPath(),\n deepNode\n );\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 * 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 */\nexport function writeTreeGetCompleteWriteData(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, 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 writeIdsToExclude - An optional set to be excluded\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeCalcCompleteEventCache(\n writeTree: WriteTree,\n treePath: Path,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n const subMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (compoundWriteIsEmpty(subMerge)) {\n return completeServerCache;\n } else if (\n completeServerCache == null &&\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())\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 compoundWriteApply(subMerge, layeredCache);\n }\n }\n } else {\n const merge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\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 !compoundWriteHasCompleteWrite(merge, newEmptyPath())\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 (pathContains(write.path, treePath) ||\n pathContains(treePath, write.path))\n );\n };\n const mergeAtPath = writeTreeLayerTree_(\n writeTree.allWrites,\n filter,\n treePath\n );\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return compoundWriteApply(mergeAtPath, 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 */\nexport function writeTreeCalcCompleteEventChildren(\n writeTree: WriteTree,\n treePath: Path,\n completeServerChildren: ChildrenNode | null\n) {\n let completeChildren = ChildrenNode.EMPTY_NODE as Node;\n const topLevelSet = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n treePath\n );\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 = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n completeServerChildren.forEachChild(\n PRIORITY_INDEX,\n (childName, childNode) => {\n const node = compoundWriteApply(\n compoundWriteChildCompoundWrite(merge, new Path(childName)),\n childNode\n );\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n }\n );\n // Add any complete children we have from the set\n compoundWriteGetCompleteChildren(merge).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 = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n compoundWriteGetCompleteChildren(merge).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 */\nexport function writeTreeCalcEventCacheAfterServerOverwrite(\n writeTree: WriteTree,\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 = pathChild(treePath, childPath);\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, 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 = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n if (compoundWriteIsEmpty(childMerge)) {\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 compoundWriteApply(\n childMerge,\n existingServerSnap.getChild(childPath)\n );\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 */\nexport function writeTreeCalcCompleteChild(\n writeTree: WriteTree,\n treePath: Path,\n childKey: string,\n existingServerSnap: CacheNode\n): Node | null {\n const path = pathChild(treePath, childKey);\n const shadowingNode = compoundWriteGetCompleteNode(\n writeTree.visibleWrites,\n path\n );\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n path\n );\n return compoundWriteApply(\n childMerge,\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 */\nexport function writeTreeShadowingWrite(\n writeTree: WriteTree,\n path: Path\n): Node | null {\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, 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 */\nexport function writeTreeCalcIndexedSlice(\n writeTree: WriteTree,\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 = compoundWriteChildCompoundWrite(\n writeTree.visibleWrites,\n treePath\n );\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n } else if (completeServerData != null) {\n toIterate = compoundWriteApply(merge, 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\nexport function newWriteTree(): WriteTree {\n return {\n visibleWrites: CompoundWrite.empty(),\n allWrites: [],\n lastWriteId: -1\n };\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 */\nexport interface 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 visibleWrites: CompoundWrite;\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 allWrites: WriteRecord[];\n\n lastWriteId: number;\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 writeIdsToExclude - Optional writes to exclude.\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\n */\nexport function writeTreeRefCalcCompleteEventCache(\n writeTreeRef: WriteTreeRef,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n): Node | null {\n return writeTreeCalcCompleteEventCache(\n writeTreeRef.writeTree,\n writeTreeRef.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 */\nexport function writeTreeRefCalcCompleteEventChildren(\n writeTreeRef: WriteTreeRef,\n completeServerChildren: ChildrenNode | null\n): ChildrenNode {\n return writeTreeCalcCompleteEventChildren(\n writeTreeRef.writeTree,\n writeTreeRef.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 *\n */\nexport function writeTreeRefCalcEventCacheAfterServerOverwrite(\n writeTreeRef: WriteTreeRef,\n path: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n): Node | null {\n return writeTreeCalcEventCacheAfterServerOverwrite(\n writeTreeRef.writeTree,\n writeTreeRef.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 */\nexport function writeTreeRefShadowingWrite(\n writeTreeRef: WriteTreeRef,\n path: Path\n): Node | null {\n return writeTreeShadowingWrite(\n writeTreeRef.writeTree,\n pathChild(writeTreeRef.treePath, path)\n );\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 */\nexport function writeTreeRefCalcIndexedSlice(\n writeTreeRef: WriteTreeRef,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n): NamedNode[] {\n return writeTreeCalcIndexedSlice(\n writeTreeRef.writeTree,\n writeTreeRef.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 */\nexport function writeTreeRefCalcCompleteChild(\n writeTreeRef: WriteTreeRef,\n childKey: string,\n existingServerCache: CacheNode\n): Node | null {\n return writeTreeCalcCompleteChild(\n writeTreeRef.writeTree,\n writeTreeRef.treePath,\n childKey,\n existingServerCache\n );\n}\n\n/**\n * Return a WriteTreeRef for a child.\n */\nexport function writeTreeRefChild(\n writeTreeRef: WriteTreeRef,\n childName: string\n): WriteTreeRef {\n return newWriteTreeRef(\n pathChild(writeTreeRef.treePath, childName),\n writeTreeRef.writeTree\n );\n}\n\nexport function newWriteTreeRef(\n path: Path,\n writeTree: WriteTree\n): WriteTreeRef {\n return {\n treePath: path,\n writeTree\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 */\nexport interface 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 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 readonly writeTree: WriteTree;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport {\n Change,\n ChangeType,\n changeChildAdded,\n changeChildChanged,\n changeChildRemoved\n} from './Change';\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 === ChangeType.CHILD_ADDED ||\n type === ChangeType.CHILD_CHANGED ||\n type === ChangeType.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 (\n type === ChangeType.CHILD_ADDED &&\n oldType === ChangeType.CHILD_REMOVED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n )\n );\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.delete(childKey);\n } else if (\n type === ChangeType.CHILD_REMOVED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildRemoved(childKey, oldChange.oldSnap)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_ADDED\n ) {\n this.changeMap.set(\n childKey,\n changeChildAdded(childKey, change.snapshotNode)\n );\n } else if (\n type === ChangeType.CHILD_CHANGED &&\n oldType === ChangeType.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap)\n );\n } else {\n throw assertionError(\n 'Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange\n );\n }\n } else {\n this.changeMap.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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Index } from '../snap/indexes/Index';\nimport { NamedNode, Node } from '../snap/Node';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcIndexedSlice\n} from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { ViewCache, viewCacheGetCompleteServerSnap } 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 getCompleteChild(childKey: string): Node | null;\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// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class NoCompleteChildSource_ implements CompleteChildSource {\n getCompleteChild(childKey?: string): Node | null {\n return null;\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 */\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 */\nexport class WriteTreeCompleteChildSource implements CompleteChildSource {\n constructor(\n private writes_: WriteTreeRef,\n private viewCache_: ViewCache,\n private optCompleteServerCache_: Node | null = null\n ) {}\n getCompleteChild(childKey: string): Node | null {\n const node = this.viewCache_.eventCache;\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_.serverCache;\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\n }\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 : viewCacheGetCompleteServerSnap(this.viewCache_);\n const nodes = writeTreeRefCalcIndexedSlice(\n this.writes_,\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, assertionError } from '@firebase/util';\n\nimport { AckUserWrite } from '../operation/AckUserWrite';\nimport { Merge } from '../operation/Merge';\nimport { Operation, OperationType } from '../operation/Operation';\nimport { Overwrite } from '../operation/Overwrite';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { Node } from '../snap/Node';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport {\n newEmptyPath,\n Path,\n pathChild,\n pathGetBack,\n pathGetFront,\n pathGetLength,\n pathIsEmpty,\n pathParent,\n pathPopFront\n} from '../util/Path';\nimport {\n WriteTreeRef,\n writeTreeRefCalcCompleteChild,\n writeTreeRefCalcCompleteEventCache,\n writeTreeRefCalcCompleteEventChildren,\n writeTreeRefCalcEventCacheAfterServerOverwrite,\n writeTreeRefShadowingWrite\n} from '../WriteTree';\n\nimport { Change, changeValue } from './Change';\nimport { ChildChangeAccumulator } from './ChildChangeAccumulator';\nimport {\n CompleteChildSource,\n NO_COMPLETE_CHILD_SOURCE,\n WriteTreeCompleteChildSource\n} from './CompleteChildSource';\nimport { NodeFilter } from './filter/NodeFilter';\nimport {\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap,\n viewCacheUpdateEventSnap,\n viewCacheUpdateServerSnap\n} from './ViewCache';\n\nexport interface ProcessorResult {\n readonly viewCache: ViewCache;\n readonly changes: Change[];\n}\n\nexport interface ViewProcessor {\n readonly filter: NodeFilter;\n}\n\nexport function newViewProcessor(filter: NodeFilter): ViewProcessor {\n return { filter };\n}\n\nexport function viewProcessorAssertIndexed(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache\n): void {\n assert(\n viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),\n 'Server snap not indexed'\n );\n}\n\nexport function viewProcessorApplyOperation(\n viewProcessor: ViewProcessor,\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 = viewProcessorApplyUserOverwrite(\n viewProcessor,\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.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\n newViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\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 = viewProcessorApplyUserMerge(\n viewProcessor,\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.serverCache.isFiltered();\n newViewCache = viewProcessorApplyServerMerge(\n viewProcessor,\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 = viewProcessorAckUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n ackUserWrite.affectedTree,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n newViewCache = viewProcessorRevertUserWrite(\n viewProcessor,\n oldViewCache,\n ackUserWrite.path,\n writesCache,\n completeCache,\n accumulator\n );\n }\n } else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = viewProcessorListenComplete(\n viewProcessor,\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 viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\n return { viewCache: newViewCache, changes };\n}\n\nfunction viewProcessorMaybeAddValueEvent(\n oldViewCache: ViewCache,\n newViewCache: ViewCache,\n accumulator: Change[]\n): void {\n const eventSnap = newViewCache.eventCache;\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty =\n eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\n if (\n accumulator.length > 0 ||\n !oldViewCache.eventCache.isFullyInitialized() ||\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())\n ) {\n accumulator.push(\n changeValue(viewCacheGetCompleteEventSnap(newViewCache))\n );\n }\n }\n}\n\nfunction viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n changePath: Path,\n writesCache: WriteTreeRef,\n source: CompleteChildSource,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldEventSnap = viewCache.eventCache;\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n } else {\n let newEventCache, serverNode;\n if (pathIsEmpty(changePath)) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n assert(\n viewCache.serverCache.isFullyInitialized(),\n 'If change path is empty, we must have complete server data'\n );\n if (viewCache.serverCache.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 = viewCacheGetCompleteServerSnap(viewCache);\n const completeChildren =\n serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n completeChildren\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeEventChildren,\n accumulator\n );\n } else {\n const completeNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n newEventCache = viewProcessor.filter.updateFullNode(\n viewCache.eventCache.getNode(),\n completeNode,\n accumulator\n );\n }\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n assert(\n pathGetLength(changePath) === 1,\n \"Can't have a priority with additional path components\"\n );\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.serverCache.getNode();\n // we might have overwrites for this priority\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\n changePath,\n oldEventNode,\n serverNode\n );\n if (updatedPriority != null) {\n newEventCache = viewProcessor.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 = pathPopFront(changePath);\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.serverCache.getNode();\n const eventChildUpdate =\n writeTreeRefCalcEventCacheAfterServerOverwrite(\n writesCache,\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.getNode().getImmediateChild(childKey);\n }\n } else {\n newEventChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n }\n if (newEventChild != null) {\n newEventCache = viewProcessor.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 viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath),\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n\nfunction viewProcessorApplyServerOverwrite(\n viewProcessor: ViewProcessor,\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.serverCache;\n let newServerCache;\n const serverFilter = filterServerNode\n ? viewProcessor.filter\n : viewProcessor.filter.getIndexedFilter();\n if (pathIsEmpty(changePath)) {\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 = pathGetFront(changePath);\n if (\n !oldServerSnap.isCompleteForPath(changePath) &&\n pathGetLength(changePath) > 1\n ) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = pathPopFront(changePath);\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 = viewCacheUpdateServerSnap(\n oldViewCache,\n newServerCache,\n oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath),\n serverFilter.filtersNodes()\n );\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n newViewCache,\n completeCache\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n changePath,\n writesCache,\n source,\n accumulator\n );\n}\n\nfunction viewProcessorApplyUserOverwrite(\n viewProcessor: ViewProcessor,\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.eventCache;\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n oldViewCache,\n completeCache\n );\n if (pathIsEmpty(changePath)) {\n newEventCache = viewProcessor.filter.updateFullNode(\n oldViewCache.eventCache.getNode(),\n changedSnap,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n true,\n viewProcessor.filter.filtersNodes()\n );\n } else {\n const childKey = pathGetFront(changePath);\n if (childKey === '.priority') {\n newEventCache = viewProcessor.filter.updatePriority(\n oldViewCache.eventCache.getNode(),\n changedSnap\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventCache,\n oldEventSnap.isFullyInitialized(),\n oldEventSnap.isFiltered()\n );\n } else {\n const childChangePath = pathPopFront(changePath);\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (pathIsEmpty(childChangePath)) {\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 pathGetBack(childChangePath) === '.priority' &&\n childNode.getChild(pathParent(childChangePath)).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 = viewProcessor.filter.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newChild,\n childChangePath,\n source,\n accumulator\n );\n newViewCache = viewCacheUpdateEventSnap(\n oldViewCache,\n newEventSnap,\n oldEventSnap.isFullyInitialized(),\n viewProcessor.filter.filtersNodes()\n );\n } else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n}\n\nfunction viewProcessorCacheHasChild(\n viewCache: ViewCache,\n childKey: string\n): boolean {\n return viewCache.eventCache.isCompleteForChild(childKey);\n}\n\nfunction viewProcessorApplyUserMerge(\n viewProcessor: ViewProcessor,\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 = pathChild(path, relativePath);\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = pathChild(path, relativePath);\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\n curViewCache = viewProcessorApplyUserOverwrite(\n viewProcessor,\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n return curViewCache;\n}\n\nfunction viewProcessorApplyMerge(\n viewProcessor: ViewProcessor,\n node: Node,\n merge: ImmutableTree<Node>\n): Node {\n merge.foreach((relativePath, childNode) => {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n}\n\nfunction viewProcessorApplyServerMerge(\n viewProcessor: ViewProcessor,\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.serverCache.getNode().isEmpty() &&\n !viewCache.serverCache.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: ImmutableTree<Node>;\n if (pathIsEmpty(path)) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = new ImmutableTree<Node>(null).setTree(\n path,\n changedChildren\n );\n }\n const serverNode = viewCache.serverCache.getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\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.serverCache.isCompleteForChild(childKey) &&\n childMergeTree.value === null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache.serverCache\n .getNode()\n .getImmediateChild(childKey);\n const newChild = viewProcessorApplyMerge(\n viewProcessor,\n serverChild,\n childMergeTree\n );\n curViewCache = viewProcessorApplyServerOverwrite(\n viewProcessor,\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\nfunction viewProcessorAckUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n ackPath: Path,\n affectedTree: ImmutableTree<boolean>,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\n return viewCache;\n }\n\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.serverCache.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.serverCache;\n if (affectedTree.value != null) {\n // This is an overwrite.\n if (\n (pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)\n ) {\n return viewProcessorApplyServerOverwrite(\n viewProcessor,\n viewCache,\n ackPath,\n serverCache.getNode().getChild(ackPath),\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else if (pathIsEmpty(ackPath)) {\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 = new ImmutableTree<Node>(null);\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\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 = new ImmutableTree<Node>(null);\n affectedTree.foreach((mergePath, value) => {\n const serverCachePath = pathChild(ackPath, mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(\n mergePath,\n serverCache.getNode().getChild(serverCachePath)\n );\n }\n });\n return viewProcessorApplyServerMerge(\n viewProcessor,\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n}\n\nfunction viewProcessorListenComplete(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n const oldServerNode = viewCache.serverCache;\n const newViewCache = viewCacheUpdateServerSnap(\n viewCache,\n oldServerNode.getNode(),\n oldServerNode.isFullyInitialized() || pathIsEmpty(path),\n oldServerNode.isFiltered()\n );\n return viewProcessorGenerateEventCacheAfterServerEvent(\n viewProcessor,\n newViewCache,\n path,\n writesCache,\n NO_COMPLETE_CHILD_SOURCE,\n accumulator\n );\n}\n\nfunction viewProcessorRevertUserWrite(\n viewProcessor: ViewProcessor,\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null,\n accumulator: ChildChangeAccumulator\n): ViewCache {\n let complete;\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\n return viewCache;\n } else {\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n viewCache,\n completeServerCache\n );\n const oldEventCache = viewCache.eventCache.getNode();\n let newEventCache;\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\n let newNode;\n if (viewCache.serverCache.isFullyInitialized()) {\n newNode = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n } else {\n const serverChildren = viewCache.serverCache.getNode();\n assert(\n serverChildren instanceof ChildrenNode,\n 'serverChildren would be complete if leaf node'\n );\n newNode = writeTreeRefCalcCompleteEventChildren(\n writesCache,\n serverChildren as ChildrenNode\n );\n }\n newNode = newNode as Node;\n newEventCache = viewProcessor.filter.updateFullNode(\n oldEventCache,\n newNode,\n accumulator\n );\n } else {\n const childKey = pathGetFront(path);\n let newChild = writeTreeRefCalcCompleteChild(\n writesCache,\n childKey,\n viewCache.serverCache\n );\n if (\n newChild == null &&\n viewCache.serverCache.isCompleteForChild(childKey)\n ) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n newChild,\n pathPopFront(path),\n source,\n accumulator\n );\n } else if (viewCache.eventCache.getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = viewProcessor.filter.updateChild(\n oldEventCache,\n childKey,\n ChildrenNode.EMPTY_NODE,\n pathPopFront(path),\n source,\n accumulator\n );\n } else {\n newEventCache = oldEventCache;\n }\n if (\n newEventCache.isEmpty() &&\n viewCache.serverCache.isFullyInitialized()\n ) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writeTreeRefCalcCompleteEventCache(\n writesCache,\n viewCacheGetCompleteServerSnap(viewCache)\n );\n if (complete.isLeafNode()) {\n newEventCache = viewProcessor.filter.updateFullNode(\n newEventCache,\n complete,\n accumulator\n );\n }\n }\n }\n complete =\n viewCache.serverCache.isFullyInitialized() ||\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\n return viewCacheUpdateEventSnap(\n viewCache,\n newEventCache,\n complete,\n viewProcessor.filter.filtersNodes()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { Operation, OperationType } from '../operation/Operation';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Node } from '../snap/Node';\nimport { Path, pathGetFront, pathIsEmpty } from '../util/Path';\nimport { WriteTreeRef } from '../WriteTree';\n\nimport { CacheNode } from './CacheNode';\nimport { Change, changeChildAdded, changeValue } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport {\n EventGenerator,\n eventGeneratorGenerateEventsForChanges\n} from './EventGenerator';\nimport { EventRegistration, QueryContext } from './EventRegistration';\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { queryParamsGetNodeFilter } from './QueryParams';\nimport {\n newViewCache,\n ViewCache,\n viewCacheGetCompleteEventSnap,\n viewCacheGetCompleteServerSnap\n} from './ViewCache';\nimport {\n newViewProcessor,\n ViewProcessor,\n viewProcessorApplyOperation,\n viewProcessorAssertIndexed\n} from './ViewProcessor';\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 */\nexport class View {\n processor_: ViewProcessor;\n viewCache_: ViewCache;\n eventRegistrations_: EventRegistration[] = [];\n eventGenerator_: EventGenerator;\n\n constructor(private query_: QueryContext, initialViewCache: ViewCache) {\n const params = this.query_._queryParams;\n\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = queryParamsGetNodeFilter(params);\n\n this.processor_ = newViewProcessor(filter);\n\n const initialServerCache = initialViewCache.serverCache;\n const initialEventCache = initialViewCache.eventCache;\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 this.viewCache_ = newViewCache(newEventCache, newServerCache);\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n\n get query(): QueryContext {\n return this.query_;\n }\n}\n\nexport function viewGetServerCache(view: View): Node | null {\n return view.viewCache_.serverCache.getNode();\n}\n\nexport function viewGetCompleteNode(view: View): Node | null {\n return viewCacheGetCompleteEventSnap(view.viewCache_);\n}\n\nexport function viewGetCompleteServerCache(\n view: View,\n path: Path\n): Node | null {\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\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 view.query._queryParams.loadsAllData() ||\n (!pathIsEmpty(path) &&\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())\n ) {\n return cache.getChild(path);\n }\n }\n return null;\n}\n\nexport function viewIsEmpty(view: View): boolean {\n return view.eventRegistrations_.length === 0;\n}\n\nexport function viewAddEventRegistration(\n view: View,\n eventRegistration: EventRegistration\n) {\n view.eventRegistrations_.push(eventRegistration);\n}\n\n/**\n * @param eventRegistration - If null, remove all callbacks.\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\n * @returns Cancel events, if cancelError was provided.\n */\nexport function viewRemoveEventRegistration(\n view: View,\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 = view.query._path;\n view.eventRegistrations_.forEach(registration => {\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 < view.eventRegistrations_.length; ++i) {\n const existing = view.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(view.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n view.eventRegistrations_ = remaining;\n } else {\n view.eventRegistrations_ = [];\n }\n return cancelEvents;\n}\n\n/**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n */\nexport function viewApplyOperation(\n view: View,\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 viewCacheGetCompleteServerSnap(view.viewCache_),\n 'We should always have a full cache before handling merges'\n );\n assert(\n viewCacheGetCompleteEventSnap(view.viewCache_),\n 'Missing event cache, even though we have a server cache'\n );\n }\n\n const oldViewCache = view.viewCache_;\n const result = viewProcessorApplyOperation(\n view.processor_,\n oldViewCache,\n operation,\n writesCache,\n completeServerCache\n );\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\n\n assert(\n result.viewCache.serverCache.isFullyInitialized() ||\n !oldViewCache.serverCache.isFullyInitialized(),\n 'Once a server snap is complete, it should never go back'\n );\n\n view.viewCache_ = result.viewCache;\n\n return viewGenerateEventsForChanges_(\n view,\n result.changes,\n result.viewCache.eventCache.getNode(),\n null\n );\n}\n\nexport function viewGetInitialEvents(\n view: View,\n registration: EventRegistration\n): Event[] {\n const eventSnap = view.viewCache_.eventCache;\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(changeChildAdded(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(changeValue(eventSnap.getNode()));\n }\n return viewGenerateEventsForChanges_(\n view,\n initialChanges,\n eventSnap.getNode(),\n registration\n );\n}\n\nfunction viewGenerateEventsForChanges_(\n view: View,\n changes: Change[],\n eventCache: Node,\n eventRegistration?: EventRegistration\n): Event[] {\n const registrations = eventRegistration\n ? [eventRegistration]\n : view.eventRegistrations_;\n return eventGeneratorGenerateEventsForChanges(\n view.eventGenerator_,\n changes,\n eventCache,\n registrations\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { LeafNode } from '../snap/LeafNode';\nimport { Node } from '../snap/Node';\nimport { nodeFromJSON } from '../snap/nodeFromJSON';\nimport { SyncTree, syncTreeCalcCompleteEventCache } from '../SyncTree';\n\nimport { Indexable } from './misc';\nimport { Path, pathChild } from './Path';\n\n/* It's critical for performance that we do not calculate actual values from a SyncTree\n * unless and until the value is needed. Because we expose both a SyncTree and Node\n * version of deferred value resolution, we ned a wrapper class that will let us share\n * code.\n *\n * @see https://github.com/firebase/firebase-js-sdk/issues/2487\n */\ninterface ValueProvider {\n getImmediateChild(childName: string): ValueProvider;\n node(): Node;\n}\n\nclass ExistingValueProvider implements ValueProvider {\n constructor(readonly node_: Node) {}\n\n getImmediateChild(childName: string): ValueProvider {\n const child = this.node_.getImmediateChild(childName);\n return new ExistingValueProvider(child);\n }\n\n node(): Node {\n return this.node_;\n }\n}\n\nclass DeferredValueProvider implements ValueProvider {\n private syncTree_: SyncTree;\n private path_: Path;\n\n constructor(syncTree: SyncTree, path: Path) {\n this.syncTree_ = syncTree;\n this.path_ = path;\n }\n\n getImmediateChild(childName: string): ValueProvider {\n const childPath = pathChild(this.path_, childName);\n return new DeferredValueProvider(this.syncTree_, childPath);\n }\n\n node(): Node {\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\n }\n}\n\n/**\n * Generate placeholders for deferred values.\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 */\nexport const resolveDeferredLeafValue = function (\n value: { [k: string]: unknown } | string | number | boolean,\n existingVal: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n if (!value || typeof value !== 'object') {\n return value as string | number | boolean;\n }\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\n\n if (typeof value['.sv'] === 'string') {\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\n } else if (typeof value['.sv'] === 'object') {\n return resolveComplexDeferredValue(value['.sv'], existingVal, serverValues);\n } else {\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\n }\n};\n\nconst resolveScalarDeferredValue = function (\n op: string,\n existing: ValueProvider,\n serverValues: { [k: string]: unknown }\n): string | number | boolean {\n switch (op) {\n case 'timestamp':\n return serverValues['timestamp'] as string | number | boolean;\n default:\n assert(false, 'Unexpected server value: ' + op);\n }\n};\n\nconst resolveComplexDeferredValue = function (\n op: object,\n existing: ValueProvider,\n unused: { [k: string]: unknown }\n): string | number | boolean {\n if (!op.hasOwnProperty('increment')) {\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\n }\n const delta = op['increment'];\n if (typeof delta !== 'number') {\n assert(false, 'Unexpected increment value: ' + delta);\n }\n\n const existingNode = existing.node();\n assert(\n existingNode !== null && typeof existingNode !== 'undefined',\n 'Expected ChildrenNode.EMPTY_NODE for nulls'\n );\n\n // Incrementing a non-number sets the value to the incremented amount\n if (!existingNode.isLeafNode()) {\n return delta;\n }\n\n const leaf = existingNode as LeafNode;\n const existingVal = leaf.getValue();\n if (typeof existingVal !== 'number') {\n return delta;\n }\n\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\n return existingVal + delta;\n};\n\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param path - path to which write is relative\n * @param node - new data written at path\n * @param syncTree - current data\n */\nexport const resolveDeferredValueTree = function (\n path: Path,\n node: Node,\n syncTree: SyncTree,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new DeferredValueProvider(syncTree, path),\n serverValues\n );\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 */\nexport const resolveDeferredValueSnapshot = function (\n node: Node,\n existing: Node,\n serverValues: Indexable\n): Node {\n return resolveDeferredValue(\n node,\n new ExistingValueProvider(existing),\n serverValues\n );\n};\n\nfunction resolveDeferredValue(\n node: Node,\n existingVal: ValueProvider,\n serverValues: Indexable\n): Node {\n const rawPri = node.getPriority().val() as\n | Indexable\n | boolean\n | null\n | number\n | string;\n const priority = resolveDeferredLeafValue(\n rawPri,\n existingVal.getImmediateChild('.priority'),\n serverValues\n );\n let newNode: Node;\n\n if (node.isLeafNode()) {\n const leafNode = node as LeafNode;\n const value = resolveDeferredLeafValue(\n leafNode.getValue(),\n existingVal,\n serverValues\n );\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 = resolveDeferredValue(\n childNode,\n existingVal.getImmediateChild(childName),\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { contains, safeGet } from '@firebase/util';\n\nimport { Path, pathGetFront, pathPopFront } from './Path';\nimport { each } from './util';\n\n/**\n * Node in a Tree.\n */\nexport interface TreeNode<T> {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: Record<string, TreeNode<T>>;\n childCount: number;\n value?: T;\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 * @param name - Optional name of the node.\n * @param parent - Optional parent node.\n * @param node - Optional node to wrap.\n */\n constructor(\n readonly name: string = '',\n readonly parent: Tree<T> | null = null,\n public node: TreeNode<T> = { children: {}, childCount: 0 }\n ) {}\n}\n\n/**\n * Returns a sub-Tree for the given path.\n *\n * @param pathObj - Path to look up.\n * @returns Tree for path.\n */\nexport function treeSubTree<T>(tree: Tree<T>, 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 = tree,\n next = pathGetFront(path);\n while (next !== null) {\n const childNode = safeGet(child.node.children, next) || {\n children: {},\n childCount: 0\n };\n child = new Tree<T>(next, child, childNode);\n path = pathPopFront(path);\n next = pathGetFront(path);\n }\n\n return child;\n}\n\n/**\n * Returns the data associated with this tree node.\n *\n * @returns The data or null if no data exists.\n */\nexport function treeGetValue<T>(tree: Tree<T>): T | undefined {\n return tree.node.value;\n}\n\n/**\n * Sets data to this tree node.\n *\n * @param value - Value to set.\n */\nexport function treeSetValue<T>(tree: Tree<T>, value: T | undefined): void {\n tree.node.value = value;\n treeUpdateParents(tree);\n}\n\n/**\n * @returns Whether the tree has any children.\n */\nexport function treeHasChildren<T>(tree: Tree<T>): boolean {\n return tree.node.childCount > 0;\n}\n\n/**\n * @returns Whethe rthe tree is empty (no value or children).\n */\nexport function treeIsEmpty<T>(tree: Tree<T>): boolean {\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\n}\n\n/**\n * Calls action for each child of this tree node.\n *\n * @param action - Action to be called for each child.\n */\nexport function treeForEachChild<T>(\n tree: Tree<T>,\n action: (tree: Tree<T>) => void\n): void {\n each(tree.node.children, (child: string, childTree: TreeNode<T>) => {\n action(new Tree<T>(child, tree, childTree));\n });\n}\n\n/**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param action - Action to be called for each child.\n * @param includeSelf - Whether to call action on this node as well. Defaults to\n * false.\n * @param childrenFirst - Whether to call action on children before calling it on\n * parent.\n */\nexport function treeForEachDescendant<T>(\n tree: Tree<T>,\n action: (tree: Tree<T>) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n): void {\n if (includeSelf && !childrenFirst) {\n action(tree);\n }\n\n treeForEachChild(tree, child => {\n treeForEachDescendant(child, action, true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) {\n action(tree);\n }\n}\n\n/**\n * Calls action on each ancestor node.\n *\n * @param action - Action to be called on each parent; return\n * true to abort.\n * @param includeSelf - Whether to call action on this node as well.\n * @returns true if the action callback returned true.\n */\nexport function treeForEachAncestor<T>(\n tree: Tree<T>,\n action: (tree: Tree<T>) => unknown,\n includeSelf?: boolean\n): boolean {\n let node = includeSelf ? tree : tree.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 action - Action to be called for each child.\n */\nexport function treeForEachImmediateDescendantWithValue<T>(\n tree: Tree<T>,\n action: (tree: Tree<T>) => void\n): void {\n treeForEachChild(tree, child => {\n if (treeGetValue(child) !== undefined) {\n action(child);\n } else {\n treeForEachImmediateDescendantWithValue(child, action);\n }\n });\n}\n\n/**\n * @returns The path of this tree node, as a Path.\n */\nexport function treeGetPath<T>(tree: Tree<T>) {\n return new Path(\n tree.parent === null\n ? tree.name\n : treeGetPath(tree.parent) + '/' + tree.name\n );\n}\n\n/**\n * Adds or removes this child from its parent based on whether it's empty or not.\n */\nfunction treeUpdateParents<T>(tree: Tree<T>) {\n if (tree.parent !== null) {\n treeUpdateChild(tree.parent, tree.name, tree);\n }\n}\n\n/**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param childName - The name of the child to update.\n * @param child - The child to update.\n */\nfunction treeUpdateChild<T>(tree: Tree<T>, childName: string, child: Tree<T>) {\n const childEmpty = treeIsEmpty(child);\n const childExists = contains(tree.node.children, childName);\n if (childEmpty && childExists) {\n delete tree.node.children[childName];\n tree.node.childCount--;\n treeUpdateParents(tree);\n } else if (!childEmpty && !childExists) {\n tree.node.children[childName] = child.node;\n tree.node.childCount++;\n treeUpdateParents(tree);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n contains,\n errorPrefix as errorPrefixFxn,\n safeGet,\n stringLength\n} from '@firebase/util';\n\nimport { RepoInfo } from '../RepoInfo';\n\nimport {\n Path,\n pathChild,\n pathCompare,\n pathContains,\n pathGetBack,\n pathGetFront,\n pathSlice,\n ValidationPath,\n validationPathPop,\n validationPathPush,\n validationPathToErrorString\n} from './Path';\nimport { each, isInvalidJSONNumber } from './util';\n\n/**\n * True for invalid Firebase keys\n */\nexport const INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n */\nexport const INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n\n/**\n * Maximum number of characters to allow in leaf value\n */\nexport const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\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\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\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\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 */\nexport const validateFirebaseDataArg = function (\n fnName: string,\n value: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && value === undefined) {\n return;\n }\n\n validateFirebaseData(errorPrefixFxn(fnName, 'value'), value, path);\n};\n\n/**\n * Validate a data object client-side before sending to server.\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(\n errorPrefix + 'contains undefined ' + validationPathToErrorString(path)\n );\n }\n if (typeof data === 'function') {\n throw new Error(\n errorPrefix +\n 'contains a function ' +\n validationPathToErrorString(path) +\n ' with contents = ' +\n data.toString()\n );\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(\n errorPrefix +\n 'contains ' +\n data.toString() +\n ' ' +\n validationPathToErrorString(path)\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 validationPathToErrorString(path) +\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 validationPathToErrorString(path) +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"'\n );\n }\n }\n\n validationPathPush(path, key);\n validateFirebaseData(errorPrefix, value, path);\n validationPathPop(path);\n });\n\n if (hasDotValue && hasActualChild) {\n throw new Error(\n errorPrefix +\n ' contains \".value\" child ' +\n validationPathToErrorString(path) +\n ' in addition to actual children.'\n );\n }\n }\n};\n\n/**\n * Pre-validate paths passed in the firebase function.\n */\nexport const validateFirebaseMergePaths = function (\n errorPrefix: string,\n mergePaths: Path[]\n) {\n let i, curPath: Path;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = pathSlice(curPath);\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(pathCompare);\n let prevPath: Path | null = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && pathContains(prevPath, 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 */\nexport const validateFirebaseMergeDataArg = function (\n fnName: string,\n data: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\n\n const errorPrefix = errorPrefixFxn(fnName, 'values');\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, pathChild(path, curPath));\n if (pathGetBack(curPath) === '.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 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, 'priority') +\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, 'priority') +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).'\n );\n }\n};\n\nexport const validateKey = function (\n fnName: string,\n argumentName: string,\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, argumentName) +\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\n/**\n * @internal\n */\nexport const validatePathString = function (\n fnName: string,\n argumentName: string,\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, argumentName) +\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 argumentName: string,\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, argumentName, pathString, optional);\n};\n\n/**\n * @internal\n */\nexport const validateWritablePath = function (fnName: string, path: Path) {\n if (pathGetFront(path) === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\n\nexport const validateUrl = function (\n fnName: string,\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, 'url') +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".'\n );\n }\n};\n\nexport const validateString = function (\n fnName: string,\n argumentName: string,\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, argumentName) + 'must be a valid string.'\n );\n }\n};\n\nexport const validateObject = function (\n fnName: string,\n argumentName: string,\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, argumentName) + 'must be a valid object.'\n );\n }\n};\n\nexport const validateObjectContainsKey = function (\n fnName: string,\n argumentName: string,\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, argumentName) +\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, argumentName) +\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, argumentName) +\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Path, pathContains, pathEquals } from '../util/Path';\nimport { exceptionGuard, log, logger } from '../util/util';\n\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 */\nexport class EventQueue {\n eventLists_: EventList[] = [];\n\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n */\n recursionDepth_ = 0;\n}\n\n/**\n * @param eventDataList - The new events to queue.\n */\nexport function eventQueueQueueEvents(\n eventQueue: EventQueue,\n eventDataList: Event[]\n) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList: EventList | null = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const data = eventDataList[i];\n const path = data.getPath();\n if (currList !== null && !pathEquals(path, currList.path)) {\n eventQueue.eventLists_.push(currList);\n currList = null;\n }\n\n if (currList === null) {\n currList = { events: [], path };\n }\n\n currList.events.push(data);\n }\n if (currList) {\n eventQueue.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 - The path to raise events for.\n * @param eventDataList - The new events to raise.\n */\nexport function eventQueueRaiseEventsAtPath(\n eventQueue: EventQueue,\n path: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath =>\n pathEquals(eventPath, 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 changedPath - The path to raise events for.\n * @param eventDataList - The events to raise\n */\nexport function eventQueueRaiseEventsForChangedPath(\n eventQueue: EventQueue,\n changedPath: Path,\n eventDataList: Event[]\n) {\n eventQueueQueueEvents(eventQueue, eventDataList);\n eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue,\n eventPath =>\n pathContains(eventPath, changedPath) ||\n pathContains(changedPath, eventPath)\n );\n}\n\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(\n eventQueue: EventQueue,\n predicate: (path: Path) => boolean\n) {\n eventQueue.recursionDepth_++;\n\n let sentAll = true;\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\n const eventList = eventQueue.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.path;\n if (predicate(eventPath)) {\n eventListRaise(eventQueue.eventLists_[i]);\n eventQueue.eventLists_[i] = null;\n } else {\n sentAll = false;\n }\n }\n }\n\n if (sentAll) {\n eventQueue.eventLists_ = [];\n }\n\n eventQueue.recursionDepth_--;\n}\n\ninterface EventList {\n events: Event[];\n path: Path;\n}\n\n/**\n * Iterates through the list and raises each event\n */\nfunction eventListRaise(eventList: EventList) {\n for (let i = 0; i < eventList.events.length; i++) {\n const eventData = eventList.events[i];\n if (eventData !== null) {\n eventList.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 * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n assert,\n contains,\n isEmpty,\n map,\n safeGet,\n stringify\n} from '@firebase/util';\n\nimport { ValueEventRegistration } from '../api/Reference_impl';\n\nimport { AppCheckTokenProvider } from './AppCheckTokenProvider';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { PersistentConnection } from './PersistentConnection';\nimport { ReadonlyRestClient } from './ReadonlyRestClient';\nimport { RepoInfo } from './RepoInfo';\nimport { ServerActions } from './ServerActions';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Node } from './snap/Node';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { SnapshotHolder } from './SnapshotHolder';\nimport {\n newSparseSnapshotTree,\n SparseSnapshotTree,\n sparseSnapshotTreeForEachTree,\n sparseSnapshotTreeForget,\n sparseSnapshotTreeRemember\n} from './SparseSnapshotTree';\nimport { StatsCollection } from './stats/StatsCollection';\nimport { StatsListener } from './stats/StatsListener';\nimport {\n statsManagerGetCollection,\n statsManagerGetOrCreateReporter\n} from './stats/StatsManager';\nimport { StatsReporter, statsReporterIncludeStat } from './stats/StatsReporter';\nimport {\n SyncTree,\n syncTreeAckUserWrite,\n syncTreeAddEventRegistration,\n syncTreeApplyServerMerge,\n syncTreeApplyServerOverwrite,\n syncTreeApplyTaggedQueryMerge,\n syncTreeApplyTaggedQueryOverwrite,\n syncTreeApplyUserMerge,\n syncTreeApplyUserOverwrite,\n syncTreeCalcCompleteEventCache,\n syncTreeGetServerValue,\n syncTreeRemoveEventRegistration,\n syncTreeTagForQuery\n} from './SyncTree';\nimport { Indexable } from './util/misc';\nimport {\n newEmptyPath,\n newRelativePath,\n Path,\n pathChild,\n pathGetFront,\n pathPopFront\n} from './util/Path';\nimport {\n generateWithValues,\n resolveDeferredValueSnapshot,\n resolveDeferredValueTree\n} from './util/ServerValues';\nimport {\n Tree,\n treeForEachAncestor,\n treeForEachChild,\n treeForEachDescendant,\n treeGetPath,\n treeGetValue,\n treeHasChildren,\n treeSetValue,\n treeSubTree\n} from './util/Tree';\nimport {\n beingCrawled,\n each,\n exceptionGuard,\n log,\n LUIDGenerator,\n warn\n} from './util/util';\nimport { isValidPriority, validateFirebaseData } from './util/validation';\nimport { Event } from './view/Event';\nimport {\n EventQueue,\n eventQueueQueueEvents,\n eventQueueRaiseEventsAtPath,\n eventQueueRaiseEventsForChangedPath\n} from './view/EventQueue';\nimport { EventRegistration, QueryContext } from './view/EventRegistration';\n\nconst INTERRUPT_REASON = 'repo_interrupt';\n\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other\n * things this ensure that if there's ever a bug causing a mismatch between\n * client / server hashes for some data, we won't retry indefinitely.\n */\nconst MAX_TRANSACTION_RETRIES = 25;\n\nconst 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\ninterface Transaction {\n path: Path;\n update: (a: unknown) => unknown;\n onComplete: (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => 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 * A connection to a single data repository.\n */\nexport class Repo {\n /** Key for uniquely identifying this repo, used in RepoManager */\n readonly key: string;\n\n dataUpdateCount = 0;\n infoSyncTree_: SyncTree;\n serverSyncTree_: SyncTree;\n\n stats_: StatsCollection;\n statsListener_: StatsListener | null = null;\n eventQueue_ = new EventQueue();\n nextWriteId_ = 1;\n server_: ServerActions;\n statsReporter_: StatsReporter;\n infoData_: SnapshotHolder;\n interceptServerDataCallback_: ((a: string, b: unknown) => void) | null = null;\n\n /** A list of data pieces and paths to be set when this client disconnects. */\n onDisconnect_: SparseSnapshotTree = newSparseSnapshotTree();\n\n /** Stores queues of outstanding transactions for Firebase locations. */\n transactionQueueTree_ = new Tree<Transaction[]>();\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 public forceRestClient_: boolean,\n public authTokenProvider_: AuthTokenProvider,\n public appCheckProvider_: AppCheckTokenProvider\n ) {\n // This key is intentionally not updated if RepoInfo is later changed or replaced\n this.key = this.repoInfo_.toURLString();\n }\n\n /**\n * @returns 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\nexport function repoStart(\n repo: Repo,\n appId: string,\n authOverride?: object\n): void {\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\n\n if (repo.forceRestClient_ || beingCrawled()) {\n repo.server_ = new ReadonlyRestClient(\n repo.repoInfo_,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_\n );\n\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\n } else {\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 repo.persistentConnection_ = new PersistentConnection(\n repo.repoInfo_,\n appId,\n (\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n ) => {\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\n },\n (connectStatus: boolean) => {\n repoOnConnectStatus(repo, connectStatus);\n },\n (updates: object) => {\n repoOnServerInfoUpdate(repo, updates);\n },\n repo.authTokenProvider_,\n repo.appCheckProvider_,\n authOverride\n );\n\n repo.server_ = repo.persistentConnection_;\n }\n\n repo.authTokenProvider_.addTokenChangeListener(token => {\n repo.server_.refreshAuthToken(token);\n });\n\n repo.appCheckProvider_.addTokenChangeListener(result => {\n repo.server_.refreshAppCheckToken(result.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 repo.statsReporter_ = statsManagerGetOrCreateReporter(\n repo.repoInfo_,\n () => new StatsReporter(repo.stats_, repo.server_)\n );\n\n // Used for .info.\n repo.infoData_ = new SnapshotHolder();\n repo.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents: Event[] = [];\n const node = repo.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 = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n query._path,\n node\n );\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => {}\n });\n repoUpdateInfo(repo, 'connected', false);\n\n repo.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\n const events = onComplete(status, data);\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: (query, tag) => {\n repo.server_.unlisten(query, tag);\n }\n });\n}\n\n/**\n * @returns The time in milliseconds, taking the server offset into account if we have one.\n */\nexport function repoServerTime(repo: Repo): number {\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\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 */\nexport function repoGenerateServerValues(repo: Repo): Indexable {\n return generateWithValues({\n timestamp: repoServerTime(repo)\n });\n}\n\n/**\n * Called by realtime when we get new messages from the server.\n */\nfunction repoOnDataUpdate(\n repo: Repo,\n pathString: string,\n data: unknown,\n isMerge: boolean,\n tag: number | null\n): void {\n // For testing.\n repo.dataUpdateCount++;\n const path = new Path(pathString);\n data = repo.interceptServerDataCallback_\n ? repo.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 = syncTreeApplyTaggedQueryMerge(\n repo.serverSyncTree_,\n path,\n taggedChildren,\n tag\n );\n } else {\n const taggedSnap = nodeFromJSON(data);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\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 = syncTreeApplyServerMerge(\n repo.serverSyncTree_,\n path,\n changedChildren\n );\n } else {\n const snap = nodeFromJSON(data);\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, 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 = repoRerunTransactions(repo, path);\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\n}\n\n// TODO: This should be @private but it's used by test_access.js and internal.js\nexport function repoInterceptServerData(\n repo: Repo,\n callback: ((a: string, b: unknown) => unknown) | null\n): void {\n repo.interceptServerDataCallback_ = callback;\n}\n\nfunction repoOnConnectStatus(repo: Repo, connectStatus: boolean): void {\n repoUpdateInfo(repo, 'connected', connectStatus);\n if (connectStatus === false) {\n repoRunOnDisconnectEvents(repo);\n }\n}\n\nfunction repoOnServerInfoUpdate(repo: Repo, updates: object): void {\n each(updates, (key: string, value: unknown) => {\n repoUpdateInfo(repo, key, value);\n });\n}\n\nfunction repoUpdateInfo(repo: Repo, pathString: string, value: unknown): void {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n repo.infoData_.updateSnapshot(path, newNode);\n const events = syncTreeApplyServerOverwrite(\n repo.infoSyncTree_,\n path,\n newNode\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n}\n\nfunction repoGetNextWriteId(repo: Repo): number {\n return repo.nextWriteId_++;\n}\n\n/**\n * The purpose of `getValue` is to return the latest known value\n * satisfying `query`.\n *\n * This method will first check for in-memory cached values\n * belonging to active listeners. If they are found, such values\n * are considered to be the most up-to-date.\n *\n * If the client is not connected, this method will wait until the\n * repo has established a connection and then request the value for `query`.\n * If the client is not able to retrieve the query result for another reason,\n * it reports an error.\n *\n * @param query - The query to surface a value for.\n */\nexport function repoGetValue(\n repo: Repo,\n query: QueryContext,\n eventRegistration: ValueEventRegistration\n): Promise<Node> {\n // Only active queries are cached. There is no persisted cache.\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\n if (cached != null) {\n return Promise.resolve(cached);\n }\n return repo.server_.get(query).then(\n payload => {\n const node = nodeFromJSON(payload).withIndex(\n query._queryParams.getIndex()\n );\n /**\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\n * Add an event registration,\n * Update data at the path,\n * Raise any events,\n * Cleanup the SyncTree\n */\n syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n true\n );\n let events: Event[];\n if (query._queryParams.loadsAllData()) {\n events = syncTreeApplyServerOverwrite(\n repo.serverSyncTree_,\n query._path,\n node\n );\n } else {\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\n events = syncTreeApplyTaggedQueryOverwrite(\n repo.serverSyncTree_,\n query._path,\n node,\n tag\n );\n }\n /*\n * We need to raise events in the scenario where `get()` is called at a parent path, and\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\n * ensure the corresponding child events will get fired.\n */\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n query._path,\n events\n );\n syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration,\n null,\n true\n );\n return node;\n },\n err => {\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\n return Promise.reject(new Error(err as string));\n }\n );\n}\n\nexport function repoSetWithPriority(\n repo: Repo,\n path: Path,\n newVal: unknown,\n newPriority: number | string | null,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, '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 = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n existing,\n serverValues\n );\n\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n writeId,\n true\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.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 = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\n}\n\nexport function repoUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repoLog(repo, '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 = repoGenerateServerValues(repo);\n const changedChildren: { [k: string]: Node } = {};\n each(childrenToMerge, (changedKey: string, changedValue: unknown) => {\n empty = false;\n changedChildren[changedKey] = resolveDeferredValueTree(\n pathChild(path, changedKey),\n nodeFromJSON(changedValue),\n repo.serverSyncTree_,\n serverValues\n );\n });\n\n if (!empty) {\n const writeId = repoGetNextWriteId(repo);\n const events = syncTreeApplyUserMerge(\n repo.serverSyncTree_,\n path,\n changedChildren,\n writeId\n );\n eventQueueQueueEvents(repo.eventQueue_, events);\n repo.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 = syncTreeAckUserWrite(\n repo.serverSyncTree_,\n writeId,\n !success\n );\n const affectedPath =\n clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n affectedPath,\n clearEvents\n );\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n\n each(childrenToMerge, (changedPath: string) => {\n const affectedPath = repoAbortTransactions(\n repo,\n pathChild(path, changedPath)\n );\n repoRerunTransactions(repo, affectedPath);\n });\n\n // We queued the events above, so just flush the queue here\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n }\n}\n\n/**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n */\nfunction repoRunOnDisconnectEvents(repo: Repo): void {\n repoLog(repo, 'onDisconnectEvents');\n\n const serverValues = repoGenerateServerValues(repo);\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\n sparseSnapshotTreeForEachTree(\n repo.onDisconnect_,\n newEmptyPath(),\n (path, node) => {\n const resolved = resolveDeferredValueTree(\n path,\n node,\n repo.serverSyncTree_,\n serverValues\n );\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\n }\n );\n let events: Event[] = [];\n\n sparseSnapshotTreeForEachTree(\n resolvedOnDisconnectTree,\n newEmptyPath(),\n (path, snap) => {\n events = events.concat(\n syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap)\n );\n const affectedPath = repoAbortTransactions(repo, path);\n repoRerunTransactions(repo, affectedPath);\n }\n );\n\n repo.onDisconnect_ = newSparseSnapshotTree();\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\n}\n\nexport function repoOnDisconnectCancel(\n repo: Repo,\n path: Path,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n });\n}\n\nexport function repoOnDisconnectSet(\n repo: Repo,\n path: Path,\n value: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectSetWithPriority(\n repo: Repo,\n path: Path,\n value: unknown,\n priority: unknown,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n const newNode = nodeFromJSON(value, priority);\n repo.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoOnDisconnectUpdate(\n repo: Repo,\n path: Path,\n childrenToMerge: { [k: string]: unknown },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n): void {\n if (isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\n return;\n }\n\n repo.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 sparseSnapshotTreeRemember(\n repo.onDisconnect_,\n pathChild(path, childName),\n newChildNode\n );\n });\n }\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\n }\n );\n}\n\nexport function repoAddEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\n let events;\n if (pathGetFront(query._path) === '.info') {\n events = syncTreeAddEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeAddEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoRemoveEventCallbackForQuery(\n repo: Repo,\n query: QueryContext,\n eventRegistration: EventRegistration\n): void {\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 (pathGetFront(query._path) === '.info') {\n events = syncTreeRemoveEventRegistration(\n repo.infoSyncTree_,\n query,\n eventRegistration\n );\n } else {\n events = syncTreeRemoveEventRegistration(\n repo.serverSyncTree_,\n query,\n eventRegistration\n );\n }\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\n}\n\nexport function repoInterrupt(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n}\n\nexport function repoResume(repo: Repo): void {\n if (repo.persistentConnection_) {\n repo.persistentConnection_.resume(INTERRUPT_REASON);\n }\n}\n\nexport function repoStats(repo: Repo, showDelta: boolean = false): void {\n if (typeof console === 'undefined') {\n return;\n }\n\n let stats: { [k: string]: unknown };\n if (showDelta) {\n if (!repo.statsListener_) {\n repo.statsListener_ = new StatsListener(repo.stats_);\n }\n stats = repo.statsListener_.get();\n } else {\n stats = repo.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\nexport function repoStatsIncrementCounter(repo: Repo, metric: string): void {\n repo.stats_.incrementCounter(metric);\n statsReporterIncludeStat(repo.statsReporter_, metric);\n}\n\nfunction repoLog(repo: Repo, ...varArgs: unknown[]): void {\n let prefix = '';\n if (repo.persistentConnection_) {\n prefix = repo.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n}\n\nexport function repoCallOnCompleteCallback(\n repo: Repo,\n callback: ((status: Error | null, errorReason?: string) => void) | null,\n status: string,\n errorReason?: string | null\n): void {\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\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/**\n * Creates a new transaction, adds it to the transactions we're tracking, and\n * sends it to the server if possible.\n *\n * @param path - Path at which to do transaction.\n * @param transactionUpdate - Update callback.\n * @param onComplete - Completion callback.\n * @param unwatcher - Function that will be called when the transaction no longer\n * need data updates for `path`.\n * @param applyLocally - Whether or not to make intermediate results visible\n */\nexport function repoStartTransaction(\n repo: Repo,\n path: Path,\n transactionUpdate: (a: unknown) => unknown,\n onComplete: ((error: Error, committed: boolean, node: Node) => void) | null,\n unwatcher: () => void,\n applyLocally: boolean\n): void {\n repoLog(repo, 'transaction on ' + path);\n\n // Initialize transaction.\n const transaction: Transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out\n // which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n\n // Run transaction initially.\n const currentState = repoGetLatestState(repo, path, undefined);\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 transaction.onComplete(null, false, transaction.currentInputSnapshot);\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 = treeSubTree(repo.transactionQueueTree_, path);\n const nodeQueue = treeGetValue(queueNode) || [];\n nodeQueue.push(transaction);\n\n treeSetValue(queueNode, nodeQueue);\n\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our\n // transaction state, since the user could start new transactions from the\n // 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 syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n\n const serverValues = repoGenerateServerValues(repo);\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n currentState,\n serverValues\n );\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n\n const events = syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n path,\n newNode,\n transaction.currentWriteId,\n transaction.applyLocally\n );\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\n\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n }\n}\n\n/**\n * @param excludeSets - A specific set to exclude\n */\nfunction repoGetLatestState(\n repo: Repo,\n path: Path,\n excludeSets?: number[]\n): Node {\n return (\n syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\n ChildrenNode.EMPTY_NODE\n );\n}\n\n/**\n * Sends any already-run transactions that aren't waiting for outstanding\n * transactions to complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively\n * with a particular transactionQueueTree node to recurse through the tree.\n *\n * @param node - transactionQueueTree node to start at.\n */\nfunction repoSendReadyTransactions(\n repo: Repo,\n node: Tree<Transaction[]> = repo.transactionQueueTree_\n): void {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n repoPruneCompletedTransactionsBelowNode(repo, node);\n }\n\n if (treeGetValue(node)) {\n const queue = repoBuildTransactionQueue(repo, 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 repoSendTransactionQueue(repo, treeGetPath(node), queue);\n }\n } else if (treeHasChildren(node)) {\n treeForEachChild(node, childNode => {\n repoSendReadyTransactions(repo, childNode);\n });\n }\n}\n\n/**\n * Given a list of run transactions, send them to the server and then handle\n * the result (success or failure).\n *\n * @param path - The location of the queue.\n * @param queue - Queue of transactions under the specified location.\n */\nfunction repoSendTransactionQueue(\n repo: Repo,\n path: Path,\n queue: Transaction[]\n): void {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(txn => {\n return txn.currentWriteId;\n });\n const latestState = repoGetLatestState(repo, 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 = newRelativePath(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 repo.server_.put(\n pathToSend.toString(),\n dataToSend,\n (status: string) => {\n repoLog(repo, '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\n // transaction state, since the callback could trigger more\n // 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 syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId)\n );\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this\n // transaction is complete, it should be set\n callbacks.push(() =>\n queue[i].onComplete(\n null,\n true,\n queue[i].currentOutputSnapshotResolved\n )\n );\n }\n queue[i].unwatcher();\n }\n\n // Now remove the completed transactions.\n repoPruneCompletedTransactionsBelowNode(\n repo,\n treeSubTree(repo.transactionQueueTree_, path)\n );\n // There may be pending transactions that we can now send.\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, 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 repoRerunTransactions(repo, 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\n * is the path at which events need to be raised for.\n *\n * @param changedPath - The path in mergedData that changed.\n * @returns The rootmost path that was affected by rerunning transactions.\n */\nfunction repoRerunTransactions(repo: Repo, changedPath: Path): Path {\n const rootMostTransactionNode = repoGetAncestorTransactionNode(\n repo,\n changedPath\n );\n const path = treeGetPath(rootMostTransactionNode);\n\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\n repoRerunTransactionQueue(repo, queue, path);\n\n return path;\n}\n\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted\n * transactions and whatnot).\n *\n * @param queue - The queue of transactions to run.\n * @param path - The path the queue is for.\n */\nfunction repoRerunTransactionQueue(\n repo: Repo,\n queue: Transaction[],\n path: Path\n): void {\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\n // transaction state, since the callback could trigger more transactions or\n // 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 = newRelativePath(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 syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n } else {\n // This code reruns a transaction\n const currentNode = repoGetLatestState(\n repo,\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 = repoGenerateServerValues(repo);\n const newNodeResolved = resolveDeferredValueSnapshot(\n newDataNode,\n currentNode,\n serverValues\n );\n\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = repoGetNextWriteId(repo);\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(\n syncTreeApplyUserOverwrite(\n repo.serverSyncTree_,\n transaction.path,\n newNodeResolved,\n transaction.currentWriteId,\n transaction.applyLocally\n )\n );\n events = events.concat(\n syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true)\n );\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(\n syncTreeAckUserWrite(\n repo.serverSyncTree_,\n transaction.currentWriteId,\n true\n )\n );\n }\n }\n }\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, 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\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\n // 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 callbacks.push(() =>\n queue[i].onComplete(null, false, queue[i].currentInputSnapshot)\n );\n } else {\n callbacks.push(() =>\n queue[i].onComplete(new Error(abortReason), false, null)\n );\n }\n }\n }\n }\n\n // Clean up completed transactions.\n repoPruneCompletedTransactionsBelowNode(repo, repo.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 repoSendReadyTransactions(repo, repo.transactionQueueTree_);\n}\n\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending\n * transaction on it, or just returns the node for the given path if there are\n * no pending transactions on any ancestor.\n *\n * @param path - The location to start at.\n * @returns The rootmost node with a transaction.\n */\nfunction repoGetAncestorTransactionNode(\n repo: Repo,\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\n // find a node with pending transactions.\n let transactionNode = repo.transactionQueueTree_;\n front = pathGetFront(path);\n while (front !== null && treeGetValue(transactionNode) === undefined) {\n transactionNode = treeSubTree(transactionNode, front);\n path = pathPopFront(path);\n front = pathGetFront(path);\n }\n\n return transactionNode;\n}\n\n/**\n * Builds the queue of all transactions at or below the specified\n * transactionNode.\n *\n * @param transactionNode\n * @returns The generated queue.\n */\nfunction repoBuildTransactionQueue(\n repo: Repo,\n transactionNode: Tree<Transaction[]>\n): Transaction[] {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue: Transaction[] = [];\n repoAggregateTransactionQueuesForNode(\n repo,\n transactionNode,\n transactionQueue\n );\n\n // Sort them by the order the transactions were created.\n transactionQueue.sort((a, b) => a.order - b.order);\n\n return transactionQueue;\n}\n\nfunction repoAggregateTransactionQueuesForNode(\n repo: Repo,\n node: Tree<Transaction[]>,\n queue: Transaction[]\n): void {\n const nodeQueue = treeGetValue(node);\n if (nodeQueue) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n treeForEachChild(node, child => {\n repoAggregateTransactionQueuesForNode(repo, child, queue);\n });\n}\n\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n */\nfunction repoPruneCompletedTransactionsBelowNode(\n repo: Repo,\n node: Tree<Transaction[]>\n): void {\n const queue = treeGetValue(node);\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 treeSetValue(node, queue.length > 0 ? queue : undefined);\n }\n\n treeForEachChild(node, childNode => {\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\n });\n}\n\n/**\n * Aborts all transactions on ancestors or descendants of the specified path.\n * Called when doing a set() or update() since we consider them incompatible\n * with transactions.\n *\n * @param path - Path for which we want to abort related transactions.\n */\nfunction repoAbortTransactions(repo: Repo, path: Path): Path {\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\n\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\n\n treeForEachAncestor(transactionNode, (node: Tree<Transaction[]>) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n repoAbortTransactionsOnNode(repo, transactionNode);\n\n treeForEachDescendant(transactionNode, (node: Tree<Transaction[]>) => {\n repoAbortTransactionsOnNode(repo, node);\n });\n\n return affectedPath;\n}\n\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param node - Node to abort transactions for.\n */\nfunction repoAbortTransactionsOnNode(\n repo: Repo,\n node: Tree<Transaction[]>\n): void {\n const queue = treeGetValue(node);\n if (queue) {\n // Queue up the callbacks and fire them after cleaning up all of our\n // transaction state, since the callback could trigger more transactions\n // or sets.\n const callbacks = [];\n\n // Go through queue. Any already-sent transactions must be marked for\n // abort, while the unsent ones 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 syncTreeAckUserWrite(\n repo.serverSyncTree_,\n queue[i].currentWriteId,\n true\n )\n );\n if (queue[i].onComplete) {\n callbacks.push(\n queue[i].onComplete.bind(null, new Error('set'), false, null)\n );\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n treeSetValue(node, undefined);\n } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n\n // Now fire the callbacks.\n eventQueueRaiseEventsForChangedPath(\n repo.eventQueue_,\n treeGetPath(node),\n events\n );\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RepoInfo } from '../../RepoInfo';\nimport { Path } from '../Path';\nimport { warnIfPageIsSecure, warn, fatal } from '../util';\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 * @returns 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\nexport const parseRepoInfo = function (\n dataURL: string,\n nodeAdmin: boolean\n): { repoInfo: RepoInfo; path: Path } {\n const parsedUrl = parseDatabaseURL(dataURL),\n namespace = parsedUrl.namespace;\n\n if (parsedUrl.domain === 'firebase.com') {\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 nodeAdmin,\n /*persistenceKey=*/ '',\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain\n ),\n path: new Path(parsedUrl.pathString)\n };\n};\n\nexport const parseDatabaseURL = function (dataURL: string): {\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 = host.length;\n }\n\n const hostWithoutPort = host.slice(0, colonInd);\n if (hostWithoutPort.toLowerCase() === 'localhost') {\n domain = 'localhost';\n } else if (hostWithoutPort.split('.').length <= 2) {\n domain = hostWithoutPort;\n } else {\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\n const dotInd = host.indexOf('.');\n subdomain = host.substring(0, dotInd).toLowerCase();\n domain = host.substring(dotInd + 1);\n // Normalize namespaces to lowercase to share storage / connection.\n namespace = subdomain;\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport {\n tryParseInt,\n MAX_NAME,\n MIN_NAME,\n INTEGER_32_MIN,\n INTEGER_32_MAX\n} from '../util/util';\n\n// Modeled after base64 web-safe chars, but ordered by ASCII.\nconst PUSH_CHARS =\n '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n\nconst MIN_PUSH_CHAR = '-';\n\nconst MAX_PUSH_CHAR = 'z';\n\nconst MAX_KEY_LEN = 786;\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 // 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\nexport const successor = function (key: string) {\n if (key === '' + INTEGER_32_MAX) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\n return MIN_PUSH_CHAR;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt + 1);\n }\n const next = new Array(key.length);\n\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n\n if (next.length < MAX_KEY_LEN) {\n next.push(MIN_PUSH_CHAR);\n return next.join('');\n }\n\n let i = next.length - 1;\n\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\n i--;\n }\n\n // `successor` was called on the largest possible key, so return the\n // MAX_NAME, which sorts larger than all keys.\n if (i === -1) {\n return MAX_NAME;\n }\n\n const source = next[i];\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\n next[i] = sourcePlusOne;\n\n return next.slice(0, i + 1).join('');\n};\n\n// `key` is assumed to be non-empty.\nexport const predecessor = function (key: string) {\n if (key === '' + INTEGER_32_MIN) {\n return MIN_NAME;\n }\n const keyAsInt: number = tryParseInt(key);\n if (keyAsInt != null) {\n return '' + (keyAsInt - 1);\n }\n const next = new Array(key.length);\n for (let i = 0; i < next.length; i++) {\n next[i] = key.charAt(i);\n }\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\n // than that, `predecessor(predecessor(key))`, is\n //\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\n //\n // analogous to increment/decrement for base-10 integers.\n //\n // This works because lexigographic comparison works character-by-character,\n // using length as a tie-breaker if one key is a prefix of the other.\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\n if (next.length === 1) {\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\n return '' + INTEGER_32_MAX;\n }\n delete next[next.length - 1];\n return next.join('');\n }\n // Replace the last character with it's immediate predecessor, and\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\n // lexicographically largest possible key smaller than `key`.\n next[next.length - 1] = PUSH_CHARS.charAt(\n PUSH_CHARS.indexOf(next[next.length - 1]) - 1\n );\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { stringify } from '@firebase/util';\n\nimport { DataSnapshot as ExpDataSnapshot } from '../../api/Reference_impl';\nimport { Path } from '../util/Path';\n\nimport { EventRegistration } from './EventRegistration';\n\n/**\n * Encapsulates the data needed to raise an event\n * @interface\n */\nexport interface Event {\n getPath(): Path;\n\n getEventType(): string;\n\n getEventRunner(): () => void;\n\n toString(): string;\n}\n\n/**\n * One of the following strings: \"value\", \"child_added\", \"child_changed\",\n * \"child_removed\", or \"child_moved.\"\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 */\nexport class DataEvent implements Event {\n /**\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\n * @param eventRegistration - The function to call to with the event data. User provided\n * @param snapshot - The data backing the event\n * @param 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: ExpDataSnapshot,\n public prevName?: string | null\n ) {}\n getPath(): Path {\n const ref = this.snapshot.ref;\n if (this.eventType === 'value') {\n return ref._path;\n } else {\n return ref.parent._path;\n }\n }\n getEventType(): string {\n return this.eventType;\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\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 constructor(\n public eventRegistration: EventRegistration,\n public error: Error,\n public path: Path\n ) {}\n getPath(): Path {\n return this.path;\n }\n getEventType(): string {\n return 'cancel';\n }\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n toString(): string {\n return this.path.toString() + ':cancel';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert } from '@firebase/util';\n\nimport { DataSnapshot } from '../../api/Reference_impl';\nimport { Repo } from '../Repo';\nimport { Path } from '../util/Path';\n\nimport { Change } from './Change';\nimport { CancelEvent, Event } from './Event';\nimport { QueryParams } from './QueryParams';\n\n/**\n * A user callback. Callbacks issues from the Legacy SDK maintain references\n * to the original user-issued callbacks, which allows equality\n * comparison by reference even though this callbacks are wrapped before\n * they can be passed to the firebase@exp SDK.\n *\n * @internal\n */\nexport interface UserCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: string | null): unknown;\n userCallback?: unknown;\n context?: object | null;\n}\n\n/**\n * A wrapper class that converts events from the database@exp SDK to the legacy\n * Database SDK. Events are not converted directly as event registration relies\n * on reference comparison of the original user callback (see `matches()`) and\n * relies on equality of the legacy SDK's `context` object.\n */\nexport class CallbackContext {\n constructor(\n private readonly snapshotCallback: UserCallback,\n private readonly cancelCallback?: (error: Error) => unknown\n ) {}\n\n onValue(\n expDataSnapshot: DataSnapshot,\n previousChildName?: string | null\n ): void {\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\n }\n\n onCancel(error: Error): void {\n assert(\n this.hasCancelCallback,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n return this.cancelCallback.call(null, error);\n }\n\n get hasCancelCallback(): boolean {\n return !!this.cancelCallback;\n }\n\n matches(other: CallbackContext): boolean {\n return (\n this.snapshotCallback === other.snapshotCallback ||\n (this.snapshotCallback.userCallback !== undefined &&\n this.snapshotCallback.userCallback ===\n other.snapshotCallback.userCallback &&\n this.snapshotCallback.context === other.snapshotCallback.context)\n );\n }\n}\n\nexport interface QueryContext {\n readonly _queryIdentifier: string;\n readonly _queryObject: object;\n readonly _repo: Repo;\n readonly _path: Path;\n readonly _queryParams: QueryParams;\n}\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 */\n respondsTo(eventType: string): boolean;\n\n createEvent(change: Change, query: QueryContext): Event;\n\n /**\n * Given event data, return a function to trigger the user's callback\n */\n getEventRunner(eventData: Event): () => void;\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null;\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 */\n hasAnyCallback(): boolean;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoOnDisconnectCancel,\n repoOnDisconnectSet,\n repoOnDisconnectSetWithPriority,\n repoOnDisconnectUpdate\n} from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport {\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validatePriority,\n validateWritablePath\n} from '../core/util/validation';\n\n/**\n * The `onDisconnect` class allows you to write or clear data when your client\n * disconnects from the Database server. These updates occur whether your\n * client disconnects cleanly or not, so you can rely on them to clean up data\n * even if a connection is dropped or a client crashes.\n *\n * The `onDisconnect` class is most commonly used to manage presence in\n * applications where it is useful to detect how many clients are connected and\n * when other clients disconnect. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * To avoid problems when a connection is dropped before the requests can be\n * transferred to the Database server, these functions should be called before\n * writing any data.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time you reconnect.\n */\nexport class OnDisconnect {\n /** @hideconstructor */\n constructor(private _repo: Repo, private _path: Path) {}\n\n /**\n * Cancels all previously queued `onDisconnect()` set or update events for this\n * location and all children.\n *\n * If a write has been queued for this location via a `set()` or `update()` at a\n * parent location, the write at this location will be canceled, though writes\n * to sibling locations will still occur.\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n cancel(): Promise<void> {\n const deferred = new Deferred<void>();\n repoOnDisconnectCancel(\n this._repo,\n this._path,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is deleted when the client is disconnected\n * (due to closing the browser, navigating to a new page, or network issues).\n *\n * @returns Resolves when synchronization to the server is complete.\n */\n remove(): Promise<void> {\n validateWritablePath('OnDisconnect.remove', this._path);\n const deferred = new Deferred<void>();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value when the\n * client is disconnected (due to closing the browser, navigating to a new page,\n * or network issues).\n *\n * `set()` is especially useful for implementing \"presence\" systems, where a\n * value should be changed or cleared when a user disconnects so that they\n * appear \"offline\" to other users. See\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information.\n *\n * Note that `onDisconnect` operations are only triggered once. If you want an\n * operation to occur each time a disconnect occurs, you'll need to re-establish\n * the `onDisconnect` operations each time.\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n set(value: unknown): Promise<void> {\n validateWritablePath('OnDisconnect.set', this._path);\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\n const deferred = new Deferred<void>();\n repoOnDisconnectSet(\n this._repo,\n this._path,\n value,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Ensures the data at this location is set to the specified value and priority\n * when the client is disconnected (due to closing the browser, navigating to a\n * new page, or network issues).\n *\n * @param value - The value to be written to this location on disconnect (can\n * be an object, array, string, number, boolean, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when synchronization to the Database is complete.\n */\n setWithPriority(\n value: unknown,\n priority: number | string | null\n ): Promise<void> {\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\n validateFirebaseDataArg(\n 'OnDisconnect.setWithPriority',\n value,\n this._path,\n false\n );\n validatePriority('OnDisconnect.setWithPriority', priority, false);\n\n const deferred = new Deferred<void>();\n repoOnDisconnectSetWithPriority(\n this._repo,\n this._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n\n /**\n * Writes multiple values at this location when the client is disconnected (due\n * to closing the browser, navigating to a new page, or network issues).\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\n * from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * @param values - Object containing multiple values.\n * @returns Resolves when synchronization to the Database is complete.\n */\n update(values: object): Promise<void> {\n validateWritablePath('OnDisconnect.update', this._path);\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n values,\n this._path,\n false\n );\n const deferred = new Deferred<void>();\n repoOnDisconnectUpdate(\n this._repo,\n this._path,\n values as Record<string, unknown>,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assert, getModularInstance, Deferred } from '@firebase/util';\n\nimport {\n Repo,\n repoAddEventCallbackForQuery,\n repoGetValue,\n repoRemoveEventCallbackForQuery,\n repoServerTime,\n repoSetWithPriority,\n repoUpdate\n} from '../core/Repo';\nimport { ChildrenNode } from '../core/snap/ChildrenNode';\nimport { Index } from '../core/snap/indexes/Index';\nimport { KEY_INDEX } from '../core/snap/indexes/KeyIndex';\nimport { PathIndex } from '../core/snap/indexes/PathIndex';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';\nimport { Node } from '../core/snap/Node';\nimport { syncPointSetReferenceConstructor } from '../core/SyncPoint';\nimport { syncTreeSetReferenceConstructor } from '../core/SyncTree';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { nextPushId } from '../core/util/NextPushId';\nimport {\n Path,\n pathEquals,\n pathGetBack,\n pathGetFront,\n pathChild,\n pathParent,\n pathToUrlEncodedString,\n pathIsEmpty\n} from '../core/util/Path';\nimport {\n fatal,\n MAX_NAME,\n MIN_NAME,\n ObjectToUniqueKey\n} from '../core/util/util';\nimport {\n isValidPriority,\n validateFirebaseDataArg,\n validateFirebaseMergeDataArg,\n validateKey,\n validatePathString,\n validatePriority,\n validateRootPathString,\n validateUrl,\n validateWritablePath\n} from '../core/util/validation';\nimport { Change } from '../core/view/Change';\nimport { CancelEvent, DataEvent, EventType } from '../core/view/Event';\nimport {\n CallbackContext,\n EventRegistration,\n QueryContext,\n UserCallback\n} from '../core/view/EventRegistration';\nimport {\n QueryParams,\n queryParamsEndAt,\n queryParamsEndBefore,\n queryParamsGetQueryObject,\n queryParamsLimitToFirst,\n queryParamsLimitToLast,\n queryParamsOrderBy,\n queryParamsStartAfter,\n queryParamsStartAt\n} from '../core/view/QueryParams';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './OnDisconnect';\nimport {\n ListenOptions,\n Query as Query,\n DatabaseReference,\n Unsubscribe,\n ThenableReference\n} from './Reference';\n\n/**\n * @internal\n */\nexport class QueryImpl implements Query, QueryContext {\n /**\n * @hideconstructor\n */\n constructor(\n readonly _repo: Repo,\n readonly _path: Path,\n readonly _queryParams: QueryParams,\n readonly _orderByCalled: boolean\n ) {}\n\n get key(): string | null {\n if (pathIsEmpty(this._path)) {\n return null;\n } else {\n return pathGetBack(this._path);\n }\n }\n\n get ref(): DatabaseReference {\n return new ReferenceImpl(this._repo, this._path);\n }\n\n get _queryIdentifier(): string {\n const obj = queryParamsGetQueryObject(this._queryParams);\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\n\n /**\n * An object representation of the query parameters used by this Query.\n */\n get _queryObject(): object {\n return queryParamsGetQueryObject(this._queryParams);\n }\n\n isEqual(other: QueryImpl | null): boolean {\n other = getModularInstance(other);\n if (!(other instanceof QueryImpl)) {\n return false;\n }\n\n const sameRepo = this._repo === other._repo;\n const samePath = pathEquals(this._path, other._path);\n const sameQueryIdentifier =\n this._queryIdentifier === other._queryIdentifier;\n\n return sameRepo && samePath && sameQueryIdentifier;\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n toString(): string {\n return this._repo.toString() + pathToUrlEncodedString(this._path);\n }\n}\n\n/**\n * Validates that no other order by call has been made\n */\nfunction validateNoPreviousOrderByCall(query: QueryImpl, fnName: string) {\n if (query._orderByCalled === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n}\n\n/**\n * Validates start/end values for queries.\n */\nfunction 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(), startAfter(), ' +\n 'endAt(), endBefore(), 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 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\n '(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(), startAfter(), endAt(), endBefore(), or ' +\n 'equalTo() cannot be an object.'\n );\n }\n }\n}\n\n/**\n * Validates that limit* has been called with the correct combination of parameters\n */\nfunction 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(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\n 'limitToFirst() or limitToLast() instead.'\n );\n }\n}\n/**\n * @internal\n */\nexport class ReferenceImpl extends QueryImpl implements DatabaseReference {\n /** @hideconstructor */\n constructor(repo: Repo, path: Path) {\n super(repo, path, new QueryParams(), false);\n }\n\n get parent(): ReferenceImpl | null {\n const parentPath = pathParent(this._path);\n return parentPath === null\n ? null\n : new ReferenceImpl(this._repo, parentPath);\n }\n\n get root(): ReferenceImpl {\n let ref: ReferenceImpl = this;\n while (ref.parent !== null) {\n ref = ref.parent;\n }\n return ref;\n }\n}\n\n/**\n * A `DataSnapshot` contains data from a Database location.\n *\n * Any time you read data from the Database, you receive the data as a\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\n * JavaScript object by calling the `val()` method. Alternatively, you can\n * traverse into the snapshot by calling `child()` to return child snapshots\n * (which you could then call `val()` on).\n *\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\n * a Database location. It cannot be modified and will never change (to modify\n * data, you always call the `set()` method on a `Reference` directly).\n */\nexport class DataSnapshot {\n /**\n * @param _node - A SnapshotNode to wrap.\n * @param ref - The location this snapshot came from.\n * @param _index - The iteration order for this snapshot\n * @hideconstructor\n */\n constructor(\n readonly _node: Node,\n /**\n * The location of this DataSnapshot.\n */\n readonly ref: DatabaseReference,\n readonly _index: Index\n ) {}\n\n /**\n * Gets the priority value of the data in this `DataSnapshot`.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\n * ).\n */\n get priority(): string | number | null {\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 * The key (last part of the path) of the location of this `DataSnapshot`.\n *\n * The last token in a Database location is considered its key. For example,\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\n * `DataSnapshot` will return the key for the location that generated it.\n * However, accessing the key on the root URL of a Database will return\n * `null`.\n */\n get key(): string | null {\n return this.ref.key;\n }\n\n /** Returns the number of child properties of this `DataSnapshot`. */\n get size(): number {\n return this._node.numChildren();\n }\n\n /**\n * Gets another `DataSnapshot` for the location at the specified relative path.\n *\n * Passing a relative path to the `child()` method of a DataSnapshot returns\n * another `DataSnapshot` for the location at the specified relative path. The\n * relative path can either be a simple child name (for example, \"ada\") or a\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\n * whose value is `null`) is returned.\n *\n * @param path - A relative path to the location of child data.\n */\n child(path: string): DataSnapshot {\n const childPath = new Path(path);\n const childRef = child(this.ref, path);\n return new DataSnapshot(\n this._node.getChild(childPath),\n childRef,\n PRIORITY_INDEX\n );\n }\n /**\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\n * efficient than using `snapshot.val() !== null`.\n */\n exists(): boolean {\n return !this._node.isEmpty();\n }\n\n /**\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\n *\n * The `exportVal()` method is similar to `val()`, except priority information\n * is included (if available), making it suitable for backing up your data.\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exportVal(): any {\n return this._node.val(true);\n }\n\n /**\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\n *\n * Because of the way JavaScript objects work, the ordering of data in the\n * JavaScript object returned by `val()` is not guaranteed to match the\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\n * where `forEach()` comes in handy. It guarantees the children of a\n * `DataSnapshot` will be iterated in their query order.\n *\n * If no explicit `orderBy*()` method is used, results are returned\n * ordered by key (unless priorities are used, in which case, results are\n * returned by priority).\n *\n * @param action - A function that will be called for each child DataSnapshot.\n * The callback can return true to cancel further enumeration.\n * @returns true if enumeration was canceled due to your callback returning\n * true.\n */\n forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean {\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, child(this.ref, key), PRIORITY_INDEX)\n );\n });\n }\n\n /**\n * Returns true if the specified child path has (non-null) data.\n *\n * @param path - A relative path to the location of a potential child.\n * @returns `true` if data exists at the specified child path; else\n * `false`.\n */\n hasChild(path: string): boolean {\n const childPath = new Path(path);\n return !this._node.getChild(childPath).isEmpty();\n }\n\n /**\n * Returns whether or not the `DataSnapshot` has any non-`null` child\n * properties.\n *\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\n * children. If it does, you can enumerate them using `forEach()`. If it\n * doesn't, then either this snapshot contains a primitive value (which can be\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\n * `null`).\n *\n * @returns true if this snapshot has any children; else false.\n */\n hasChildren(): boolean {\n if (this._node.isLeafNode()) {\n return false;\n } else {\n return !this._node.isEmpty();\n }\n }\n\n /**\n * Returns a JSON-serializable representation of this object.\n */\n toJSON(): object | null {\n return this.exportVal();\n }\n\n /**\n * Extracts a JavaScript value from a `DataSnapshot`.\n *\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\n * scalar type (string, number, or boolean), an array, or an object. It may\n * also return null, indicating that the `DataSnapshot` is empty (contains no\n * data).\n *\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\n * Array, string, number, boolean, or `null`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n val(): any {\n return this._node.val();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\n/**\n *\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided path. If no path is provided, the `Reference`\n * will point to the root of the Database.\n *\n * @param db - The database instance to obtain a reference for.\n * @param path - Optional path representing the location the returned\n * `Reference` will point. If not provided, the returned `Reference` will\n * point to the root of the Database.\n * @returns If a path is provided, a `Reference`\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\n * root of the Database.\n */\nexport function ref(db: Database, path?: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('ref');\n return path !== undefined ? child(db._root, path) : db._root;\n}\n\n/**\n * Returns a `Reference` representing the location in the Database\n * corresponding to the provided Firebase URL.\n *\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\n * has a different domain than the current `Database` instance.\n *\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\n * and are not applied to the returned `Reference`.\n *\n * @param db - The database instance to obtain a reference for.\n * @param url - The Firebase URL at which the returned `Reference` will\n * point.\n * @returns A `Reference` pointing to the provided\n * Firebase URL.\n */\nexport function refFromURL(db: Database, url: string): DatabaseReference {\n db = getModularInstance(db);\n db._checkNotDeleted('refFromURL');\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\n validateUrl('refFromURL', parsedURL);\n\n const repoInfo = parsedURL.repoInfo;\n if (\n !db._repo.repoInfo_.isCustomHost() &&\n repoInfo.host !== db._repo.repoInfo_.host\n ) {\n fatal(\n 'refFromURL' +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n db._repo.repoInfo_.host +\n ')'\n );\n }\n\n return ref(db, parsedURL.path.toString());\n}\n/**\n * Gets a `Reference` for the location at the specified relative path.\n *\n * The relative path can either be a simple child name (for example, \"ada\") or\n * a deeper slash-separated path (for example, \"ada/name/first\").\n *\n * @param parent - The parent location.\n * @param path - A relative path from this location to the desired child\n * location.\n * @returns The specified child location.\n */\nexport function child(\n parent: DatabaseReference,\n path: string\n): DatabaseReference {\n parent = getModularInstance(parent);\n if (pathGetFront(parent._path) === null) {\n validateRootPathString('child', 'path', path, false);\n } else {\n validatePathString('child', 'path', path, false);\n }\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\n}\n\n/**\n * Returns an `OnDisconnect` object - see\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\n * for more information on how to use it.\n *\n * @param ref - The reference to add OnDisconnect triggers for.\n */\nexport function onDisconnect(ref: DatabaseReference): OnDisconnect {\n ref = getModularInstance(ref) as ReferenceImpl;\n return new OnDisconnect(ref._repo, ref._path);\n}\n\nexport interface ThenableReferenceImpl\n extends ReferenceImpl,\n Pick<Promise<ReferenceImpl>, 'then' | 'catch'> {}\n\n/**\n * Generates a new child location using a unique key and returns its\n * `Reference`.\n *\n * This is the most common pattern for adding data to a collection of items.\n *\n * If you provide a value to `push()`, the value is written to the\n * generated location. If you don't pass a value, nothing is written to the\n * database and the child remains empty (but you can use the `Reference`\n * elsewhere).\n *\n * The unique keys generated by `push()` are ordered by the current time, so the\n * resulting list of items is chronologically sorted. The keys are also\n * designed to be unguessable (they contain 72 random bits of entropy).\n *\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\n *\n * @param parent - The parent location.\n * @param value - Optional value to be written at the generated location.\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\n * but can be used immediately as the `Reference` to the child location.\n */\nexport function push(\n parent: DatabaseReference,\n value?: unknown\n): ThenableReference {\n parent = getModularInstance(parent);\n validateWritablePath('push', parent._path);\n validateFirebaseDataArg('push', value, parent._path, true);\n const now = repoServerTime(parent._repo);\n const name = nextPushId(now);\n\n // push() returns a ThennableReference whose promise is fulfilled with a\n // regular Reference. We use child() to create handles to two different\n // references. The first is turned into a ThennableReference below by adding\n // then() and catch() methods and is used as the return value of push(). The\n // second remains a regular Reference and is used as the fulfilled value of\n // the first ThennableReference.\n const thennablePushRef: Partial<ThenableReferenceImpl> = child(\n parent,\n name\n ) as ReferenceImpl;\n const pushRef = child(parent, name) as ReferenceImpl;\n\n let promise: Promise<ReferenceImpl>;\n if (value != null) {\n promise = set(pushRef, value).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 return thennablePushRef as ThenableReferenceImpl;\n}\n\n/**\n * Removes the data at this Database location.\n *\n * Any data at child locations will also be deleted.\n *\n * The effect of the remove will be visible immediately and the corresponding\n * event 'value' will be triggered. Synchronization of the remove to the\n * Firebase servers will also be started, and the returned Promise will resolve\n * when complete. If provided, the onComplete callback will be called\n * asynchronously after synchronization has finished.\n *\n * @param ref - The location to remove.\n * @returns Resolves when remove on server is complete.\n */\nexport function remove(ref: DatabaseReference): Promise<void> {\n validateWritablePath('remove', ref._path);\n return set(ref, null);\n}\n\n/**\n * Writes data to this Database location.\n *\n * This will overwrite any data at this location and all child locations.\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\n * all data at this location and all child locations will be deleted.\n *\n * `set()` will remove any priority stored at this location, so if priority is\n * meant to be preserved, you need to use `setWithPriority()` instead.\n *\n * Note that modifying data with `set()` will cancel any pending transactions\n * at that location, so extreme care should be taken if mixing `set()` and\n * `transaction()` to modify the same data.\n *\n * A single `set()` will generate a single \"value\" event at the location where\n * the `set()` was performed.\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function set(ref: DatabaseReference, value: unknown): Promise<void> {\n ref = getModularInstance(ref);\n validateWritablePath('set', ref._path);\n validateFirebaseDataArg('set', value, ref._path, false);\n const deferred = new Deferred<void>();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n /*priority=*/ null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Sets a priority for the data at this Database location.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setPriority(\n ref: DatabaseReference,\n priority: string | number | null\n): Promise<void> {\n ref = getModularInstance(ref);\n validateWritablePath('setPriority', ref._path);\n validatePriority('setPriority', priority, false);\n const deferred = new Deferred<void>();\n repoSetWithPriority(\n ref._repo,\n pathChild(ref._path, '.priority'),\n priority,\n null,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes data the Database location. Like `set()` but also specifies the\n * priority for that data.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\n * ).\n *\n * @param ref - The location to write to.\n * @param value - The value to be written (string, number, boolean, object,\n * array, or null).\n * @param priority - The priority to be written (string, number, or null).\n * @returns Resolves when write to server is complete.\n */\nexport function setWithPriority(\n ref: DatabaseReference,\n value: unknown,\n priority: string | number | null\n): Promise<void> {\n validateWritablePath('setWithPriority', ref._path);\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\n validatePriority('setWithPriority', priority, false);\n if (ref.key === '.length' || ref.key === '.keys') {\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\n }\n\n const deferred = new Deferred<void>();\n repoSetWithPriority(\n ref._repo,\n ref._path,\n value,\n priority,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Writes multiple values to the Database at once.\n *\n * The `values` argument contains multiple property-value pairs that will be\n * written to the Database together. Each child property can either be a simple\n * property (for example, \"name\") or a relative path (for example,\n * \"name/first\") from the current location to the data to update.\n *\n * As opposed to the `set()` method, `update()` can be use to selectively update\n * only the referenced properties at the current location (instead of replacing\n * all the child properties at the current location).\n *\n * The effect of the write will be visible immediately, and the corresponding\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\n * the data to the Firebase servers will also be started, and the returned\n * Promise will resolve when complete. If provided, the `onComplete` callback\n * will be called asynchronously after synchronization has finished.\n *\n * A single `update()` will generate a single \"value\" event at the location\n * where the `update()` was performed, regardless of how many children were\n * modified.\n *\n * Note that modifying data with `update()` will cancel any pending\n * transactions at that location, so extreme care should be taken if mixing\n * `update()` and `transaction()` to modify the same data.\n *\n * Passing `null` to `update()` will remove the data at this location.\n *\n * See\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\n *\n * @param ref - The location to write to.\n * @param values - Object containing multiple values.\n * @returns Resolves when update on server is complete.\n */\nexport function update(ref: DatabaseReference, values: object): Promise<void> {\n validateFirebaseMergeDataArg('update', values, ref._path, false);\n const deferred = new Deferred<void>();\n repoUpdate(\n ref._repo,\n ref._path,\n values as Record<string, unknown>,\n deferred.wrapCallback(() => {})\n );\n return deferred.promise;\n}\n\n/**\n * Gets the most up-to-date result for this query.\n *\n * @param query - The query to run.\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\n * available, or rejects if the client is unable to return a value (e.g., if the\n * server is unreachable and there is nothing cached).\n */\nexport function get(query: Query): Promise<DataSnapshot> {\n query = getModularInstance(query) as QueryImpl;\n const callbackContext = new CallbackContext(() => {});\n const container = new ValueEventRegistration(callbackContext);\n return repoGetValue(query._repo, query, container).then(node => {\n return new DataSnapshot(\n node,\n new ReferenceImpl(query._repo, query._path),\n query._queryParams.getIndex()\n );\n });\n}\n/**\n * Represents registration for 'value' events.\n */\nexport class ValueEventRegistration implements EventRegistration {\n constructor(private callbackContext: CallbackContext) {}\n\n respondsTo(eventType: string): boolean {\n return eventType === 'value';\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n const index = query._queryParams.getIndex();\n return new DataEvent(\n 'value',\n this,\n new DataSnapshot(\n change.snapshotNode,\n new ReferenceImpl(query._repo, query._path),\n index\n )\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue((eventData as DataEvent).snapshot, null);\n }\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n } else if (!other.callbackContext || !this.callbackContext) {\n // If no callback specified, we consider it to match any callback.\n return true;\n } else {\n return other.callbackContext.matches(this.callbackContext);\n }\n }\n\n hasAnyCallback(): boolean {\n return this.callbackContext !== null;\n }\n}\n\n/**\n * Represents the registration of a child_x event.\n */\nexport class ChildEventRegistration implements EventRegistration {\n constructor(\n private eventType: string,\n private callbackContext: CallbackContext | null\n ) {}\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 this.eventType === eventToCheck;\n }\n\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.callbackContext.hasCancelCallback) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n createEvent(change: Change, query: QueryContext): DataEvent {\n assert(change.childName != null, 'Child events should have a childName.');\n const childRef = child(\n new ReferenceImpl(query._repo, query._path),\n change.childName\n );\n const index = query._queryParams.getIndex();\n return new DataEvent(\n change.type as EventType,\n this,\n new DataSnapshot(change.snapshotNode, childRef, index),\n change.prevName\n );\n }\n\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n if (eventData.getEventType() === 'cancel') {\n return () =>\n this.callbackContext.onCancel((eventData as CancelEvent).error);\n } else {\n return () =>\n this.callbackContext.onValue(\n (eventData as DataEvent).snapshot,\n (eventData as DataEvent).prevName\n );\n }\n }\n\n matches(other: EventRegistration): boolean {\n if (other instanceof ChildEventRegistration) {\n return (\n this.eventType === other.eventType &&\n (!this.callbackContext ||\n !other.callbackContext ||\n this.callbackContext.matches(other.callbackContext))\n );\n }\n\n return false;\n }\n\n hasAnyCallback(): boolean {\n return !!this.callbackContext;\n }\n}\n\nfunction addEventListener(\n query: Query,\n eventType: EventType,\n callback: UserCallback,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n) {\n let cancelCallback: ((error: Error) => unknown) | undefined;\n if (typeof cancelCallbackOrListenOptions === 'object') {\n cancelCallback = undefined;\n options = cancelCallbackOrListenOptions;\n }\n if (typeof cancelCallbackOrListenOptions === 'function') {\n cancelCallback = cancelCallbackOrListenOptions;\n }\n\n if (options && options.onlyOnce) {\n const userCallback = callback;\n const onceCallback: UserCallback = (dataSnapshot, previousChildName) => {\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n userCallback(dataSnapshot, previousChildName);\n };\n onceCallback.userCallback = callback.userCallback;\n onceCallback.context = callback.context;\n callback = onceCallback;\n }\n\n const callbackContext = new CallbackContext(\n callback,\n cancelCallback || undefined\n );\n const container =\n eventType === 'value'\n ? new ValueEventRegistration(callbackContext)\n : new ChildEventRegistration(eventType, callbackContext);\n repoAddEventCallbackForQuery(query._repo, query, container);\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onValue` event will trigger once with the initial data stored at this\n * location, and then trigger again each time the data changes. The\n * `DataSnapshot` passed to the callback will be for the location at which\n * `on()` was called. It won't trigger until the entire contents has been\n * synchronized. If the location has no data, it will be triggered with an empty\n * `DataSnapshot` (`val()` will return `null`).\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs. The\n * callback will be passed a DataSnapshot.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onValue(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'value',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildAdded` event will be triggered once for each initial child at this\n * location, and it will be triggered again every time a new child is added. The\n * `DataSnapshot` passed into the callback will reflect the data for the\n * relevant child. For ordering purposes, it is passed a second argument which\n * is a string containing the key of the previous sibling child by sort order,\n * or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildAdded(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_added',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildChanged` event will be triggered when the data stored in a child\n * (or any of its descendants) changes. Note that a single `child_changed` event\n * may represent multiple changes to the child. The `DataSnapshot` passed to the\n * callback will contain the new child contents. For ordering purposes, the\n * callback is also passed a second argument which is a string containing the\n * key of the previous sibling child by sort order, or `null` if it is the first\n * child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildChanged(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_changed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildMoved` event will be triggered when a child's sort order changes\n * such that its position relative to its siblings changes. The `DataSnapshot`\n * passed to the callback will be for the data of the child that has moved. It\n * is also passed a second argument which is a string containing the key of the\n * previous sibling child by sort order, or `null` if it is the first child.\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildMoved(\n query: Query,\n callback: (\n snapshot: DataSnapshot,\n previousChildName: string | null\n ) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_moved',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback?: (error: Error) => unknown\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\n/**\n * Listens for data changes at a particular location.\n *\n * This is the primary way to read data from a Database. Your callback\n * will be triggered for the initial data and again whenever the data changes.\n * Invoke the returned unsubscribe callback to stop receiving updates. See\n * {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}\n * for more details.\n *\n * An `onChildRemoved` event will be triggered once every time a child is\n * removed. The `DataSnapshot` passed into the callback will be the old data for\n * the child that was removed. A child will get removed when either:\n *\n * - a client explicitly calls `remove()` on that child or one of its ancestors\n * - a client calls `set(null)` on that child or one of its ancestors\n * - that child has all of its children removed\n * - there is a query in effect which now filters out the child (because it's\n * sort order changed or the max limit was hit)\n *\n * @param query - The query to run.\n * @param callback - A callback that fires when the specified event occurs.\n * The callback will be passed a DataSnapshot and a string containing the key of\n * the previous child, by sort order, or `null` if it is the first child.\n * @param cancelCallback - An optional callback that will be notified if your\n * event subscription is ever canceled because your client does not have\n * permission to read this data (or it had permission but has now lost it).\n * This callback will be passed an `Error` object indicating why the failure\n * occurred.\n * @param options - An object that can be used to configure `onlyOnce`, which\n * then removes the listener after its first invocation.\n * @returns A function that can be invoked to remove the listener.\n */\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallback: (error: Error) => unknown,\n options: ListenOptions\n): Unsubscribe;\n\nexport function onChildRemoved(\n query: Query,\n callback: (snapshot: DataSnapshot) => unknown,\n cancelCallbackOrListenOptions?: ((error: Error) => unknown) | ListenOptions,\n options?: ListenOptions\n): Unsubscribe {\n return addEventListener(\n query,\n 'child_removed',\n callback,\n cancelCallbackOrListenOptions,\n options\n );\n}\n\nexport { EventType };\n\n/**\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\n * the respective `on*` callbacks.\n *\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\n * will not automatically remove listeners registered on child nodes, `off()`\n * must also be called on any child listeners to remove the callback.\n *\n * If a callback is not specified, all callbacks for the specified eventType\n * will be removed. Similarly, if no eventType is specified, all callbacks\n * for the `Reference` will be removed.\n *\n * Individual listeners can also be removed by invoking their unsubscribe\n * callbacks.\n *\n * @param query - The query that the listener was registered with.\n * @param eventType - One of the following strings: \"value\", \"child_added\",\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\n * for the `Reference` will be removed.\n * @param callback - The callback function that was passed to `on()` or\n * `undefined` to remove all callbacks.\n */\nexport function off(\n query: Query,\n eventType?: EventType,\n callback?: (\n snapshot: DataSnapshot,\n previousChildName?: string | null\n ) => unknown\n): void {\n let container: EventRegistration | null = null;\n const expCallback = callback ? new CallbackContext(callback) : null;\n if (eventType === 'value') {\n container = new ValueEventRegistration(expCallback);\n } else if (eventType) {\n container = new ChildEventRegistration(eventType, expCallback);\n }\n repoRemoveEventCallbackForQuery(query._repo, query, container);\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'endAt'\n | 'endBefore'\n | 'startAt'\n | 'startAfter'\n | 'limitToFirst'\n | 'limitToLast'\n | 'orderByChild'\n | 'orderByKey'\n | 'orderByPriority'\n | 'orderByValue'\n | 'equalTo';\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\n * {@link orderByValue} or {@link equalTo} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint {\n /** The type of this query constraints */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided `Query` and returns a copy of the `Query` with this\n * `QueryConstraint` applied.\n */\n abstract _apply<T>(query: QueryImpl): QueryImpl;\n}\n\nclass QueryEndAtConstraint extends QueryConstraint {\n readonly type = 'endAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endAt', this._value, query._path, true);\n const newParams = queryParamsEndAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endAt: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name less than or equal\n * to the specified key.\n *\n * You can read more about `endAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to end at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end at, among the children with the previously\n * specified priority. This argument is only allowed if ordering by child,\n * value, or priority.\n */\nexport function endAt(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endAt', 'key', key, true);\n return new QueryEndAtConstraint(value, key);\n}\n\nclass QueryEndBeforeConstraint extends QueryConstraint {\n readonly type = 'endBefore';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\n const newParams = queryParamsEndBefore(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'endBefore: Starting point was already set (by another call to endAt, ' +\n 'endBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The ending point is exclusive. If only a value is provided, children\n * with a value less than the specified value will be included in the query.\n * If a key is specified, then children must have a value less than or equal\n * to the specified value and a key name less than the specified key.\n *\n * @param value - The value to end before. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to end before, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function endBefore(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('endBefore', 'key', key, true);\n return new QueryEndBeforeConstraint(value, key);\n}\n\nclass QueryStartAtConstraint extends QueryConstraint {\n readonly type = 'startAt';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAt', this._value, query._path, true);\n const newParams = queryParamsStartAt(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAt: Starting point was already set (by another call to startAt, ' +\n 'startBefore or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is inclusive, so children with exactly the specified value\n * will be included in the query. The optional key argument can be used to\n * further limit the range of the query. If it is specified, then children that\n * have exactly the specified value must also have a key name greater than or\n * equal to the specified key.\n *\n * You can read more about `startAt()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to start at. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAt(\n value: number | string | boolean | null = null,\n key?: string\n): QueryConstraint {\n validateKey('startAt', 'key', key, true);\n return new QueryStartAtConstraint(value, key);\n}\n\nclass QueryStartAfterConstraint extends QueryConstraint {\n readonly type = 'startAfter';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\n const newParams = queryParamsStartAfter(\n query._queryParams,\n this._value,\n this._key\n );\n validateLimit(newParams);\n validateQueryEndpoints(newParams);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'startAfter: Starting point was already set (by another call to startAt, ' +\n 'startAfter, or equalTo).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The starting point is exclusive. If only a value is provided, children\n * with a value greater than the specified value will be included in the query.\n * If a key is specified, then children must have a value greater than or equal\n * to the specified value and a a key name greater than the specified key.\n *\n * @param value - The value to start after. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start after. This argument is only allowed if\n * ordering by child, value, or priority.\n */\nexport function startAfter(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('startAfter', 'key', key, true);\n return new QueryStartAfterConstraint(value, key);\n}\n\nclass QueryLimitToFirstConstraint extends QueryConstraint {\n readonly type = 'limitToFirst';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToFirst: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToFirst(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that if limited to the first specific number\n * of children.\n *\n * The `limitToFirst()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the first 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToFirst()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToFirst(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToFirst: First argument must be a positive integer.');\n }\n return new QueryLimitToFirstConstraint(limit);\n}\n\nclass QueryLimitToLastConstraint extends QueryConstraint {\n readonly type = 'limitToLast';\n\n constructor(private readonly _limit: number) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n if (query._queryParams.hasLimit()) {\n throw new Error(\n 'limitToLast: Limit was already set (by another call to limitToFirst ' +\n 'or limitToLast).'\n );\n }\n return new QueryImpl(\n query._repo,\n query._path,\n queryParamsLimitToLast(query._queryParams, this._limit),\n query._orderByCalled\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that is limited to return only the last\n * specified number of children.\n *\n * The `limitToLast()` method is used to set a maximum number of children to be\n * synced for a given callback. If we set a limit of 100, we will initially only\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\n * stored in our Database, a `child_added` event will fire for each message.\n * However, if we have over 100 messages, we will only receive a `child_added`\n * event for the last 100 ordered messages. As items change, we will receive\n * `child_removed` events for each item that drops out of the active list so\n * that the total number stays at 100.\n *\n * You can read more about `limitToLast()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param limit - The maximum number of nodes to include in this query.\n */\nexport function limitToLast(limit: number): QueryConstraint {\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\n throw new Error('limitToLast: First argument must be a positive integer.');\n }\n\n return new QueryLimitToLastConstraint(limit);\n}\n\nclass QueryOrderByChildConstraint extends QueryConstraint {\n readonly type = 'orderByChild';\n\n constructor(private readonly _path: string) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByChild');\n const parsedPath = new Path(this._path);\n if (pathIsEmpty(parsedPath)) {\n throw new Error(\n 'orderByChild: cannot pass in empty path. Use orderByValue() instead.'\n );\n }\n const index = new PathIndex(parsedPath);\n const newParams = queryParamsOrderBy(query._queryParams, index);\n validateQueryEndpoints(newParams);\n\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the specified child key.\n *\n * Queries can only order by one key at a time. Calling `orderByChild()`\n * multiple times on the same query is an error.\n *\n * Firebase queries allow you to order your data by any child key on the fly.\n * However, if you know in advance what your indexes will be, you can define\n * them via the .indexOn rule in your Security Rules for better performance. See\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\n * rule for more information.\n *\n * You can read more about `orderByChild()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n *\n * @param path - The path to order by.\n */\nexport function orderByChild(path: string): QueryConstraint {\n if (path === '$key') {\n throw new Error(\n 'orderByChild: \"$key\" is invalid. Use orderByKey() instead.'\n );\n } else if (path === '$priority') {\n throw new Error(\n 'orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.'\n );\n } else if (path === '$value') {\n throw new Error(\n 'orderByChild: \"$value\" is invalid. Use orderByValue() instead.'\n );\n }\n validatePathString('orderByChild', 'path', path, false);\n return new QueryOrderByChildConstraint(path);\n}\n\nclass QueryOrderByKeyConstraint extends QueryConstraint {\n readonly type = 'orderByKey';\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByKey');\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by the key.\n *\n * Sorts the results of a query by their (ascending) key values.\n *\n * You can read more about `orderByKey()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByKey(): QueryConstraint {\n return new QueryOrderByKeyConstraint();\n}\n\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\n readonly type = 'orderByPriority';\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByPriority');\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by priority.\n *\n * Applications need not use priority but can order collections by\n * ordinary properties (see\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\n * for alternatives to priority.\n */\nexport function orderByPriority(): QueryConstraint {\n return new QueryOrderByPriorityConstraint();\n}\n\nclass QueryOrderByValueConstraint extends QueryConstraint {\n readonly type = 'orderByValue';\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateNoPreviousOrderByCall(query, 'orderByValue');\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\n validateQueryEndpoints(newParams);\n return new QueryImpl(\n query._repo,\n query._path,\n newParams,\n /*orderByCalled=*/ true\n );\n }\n}\n\n/**\n * Creates a new `QueryConstraint` that orders by value.\n *\n * If the children of a query are all scalar values (string, number, or\n * boolean), you can order the results by their (ascending) values.\n *\n * You can read more about `orderByValue()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\n */\nexport function orderByValue(): QueryConstraint {\n return new QueryOrderByValueConstraint();\n}\n\nclass QueryEqualToValueConstraint extends QueryConstraint {\n readonly type = 'equalTo';\n\n constructor(\n private readonly _value: number | string | boolean | null,\n private readonly _key?: string\n ) {\n super();\n }\n\n _apply<T>(query: QueryImpl): QueryImpl {\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\n if (query._queryParams.hasStart()) {\n throw new Error(\n 'equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\n 'equalTo).'\n );\n }\n if (query._queryParams.hasEnd()) {\n throw new Error(\n 'equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\n 'equalTo).'\n );\n }\n return new QueryEndAtConstraint(this._value, this._key)._apply(\n new QueryStartAtConstraint(this._value, this._key)._apply(query)\n );\n }\n}\n\n/**\n * Creates a `QueryConstraint` that includes children that match the specified\n * value.\n *\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\n * allows you to choose arbitrary starting and ending points for your queries.\n *\n * The optional key argument can be used to further limit the range of the\n * query. If it is specified, then children that have exactly the specified\n * value must also have exactly the specified key as their key name. This can be\n * used to filter result sets with many matches for the same value.\n *\n * You can read more about `equalTo()` in\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\n *\n * @param value - The value to match for. The argument type depends on which\n * `orderBy*()` function was used in this query. Specify a value that matches\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\n * value must be a string.\n * @param key - The child key to start at, among the children with the\n * previously specified priority. This argument is only allowed if ordering by\n * child, value, or priority.\n */\nexport function equalTo(\n value: number | string | boolean | null,\n key?: string\n): QueryConstraint {\n validateKey('equalTo', 'key', key, true);\n return new QueryEqualToValueConstraint(value, key);\n}\n\n/**\n * Creates a new immutable instance of `Query` that is extended to also include\n * additional query constraints.\n *\n * @param query - The Query instance to use as a base for the new constraints.\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query {\n let queryImpl = getModularInstance(query) as QueryImpl;\n for (const constraint of queryConstraints) {\n queryImpl = constraint._apply(queryImpl);\n }\n return queryImpl;\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 */\nsyncPointSetReferenceConstructor(ReferenceImpl);\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _FirebaseService,\n _getProvider,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport {\n getModularInstance,\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport { AppCheckTokenProvider } from '../core/AppCheckTokenProvider';\nimport {\n AuthTokenProvider,\n EmulatorTokenProvider,\n FirebaseAuthTokenProvider\n} from '../core/AuthTokenProvider';\nimport { Repo, repoInterrupt, repoResume, repoStart } from '../core/Repo';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { newEmptyPath, pathIsEmpty } from '../core/util/Path';\nimport {\n warn,\n fatal,\n log,\n enableLogging as enableLoggingImpl\n} from '../core/util/util';\nimport { validateUrl } from '../core/util/validation';\nimport { BrowserPollConnection } from '../realtime/BrowserPollConnection';\nimport { TransportManager } from '../realtime/TransportManager';\nimport { WebSocketConnection } from '../realtime/WebSocketConnection';\n\nimport { ReferenceImpl } from './Reference_impl';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\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\n/**\n * Creates and caches `Repo` instances.\n */\nconst repos: {\n [appName: string]: {\n [dbUrl: string]: Repo;\n };\n} = {};\n\n/**\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\n */\nlet useRestClient = false;\n\n/**\n * Update an existing `Repo` in place to point to a new host/port.\n */\nfunction repoManagerApplyEmulatorSettings(\n repo: Repo,\n host: string,\n port: number,\n tokenProvider?: AuthTokenProvider\n): void {\n repo.repoInfo_ = new RepoInfo(\n `${host}:${port}`,\n /* secure= */ false,\n repo.repoInfo_.namespace,\n repo.repoInfo_.webSocketOnly,\n repo.repoInfo_.nodeAdmin,\n repo.repoInfo_.persistenceKey,\n repo.repoInfo_.includeNamespaceInQueryParams,\n /*isUsingEmulator=*/ true\n );\n\n if (tokenProvider) {\n repo.authTokenProvider_ = tokenProvider;\n }\n}\n\n/**\n * This function should only ever be called to CREATE a new database instance.\n * @internal\n */\nexport function repoManagerDatabaseFromApp(\n app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n appCheckProvider?: Provider<AppCheckInternalComponentName>,\n url?: string,\n nodeAdmin?: boolean\n): Database {\n let dbUrl: string | undefined = url || app.options.databaseURL;\n if (dbUrl === undefined) {\n if (!app.options.projectId) {\n fatal(\n \"Can't determine Firebase Database URL. Be sure to include \" +\n ' a Project ID when calling firebase.initializeApp().'\n );\n }\n\n log('Using default host for project ', app.options.projectId);\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\n }\n\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n let repoInfo = parsedUrl.repoInfo;\n\n let isEmulator: boolean;\n\n let dbEmulatorHost: string | undefined = undefined;\n if (typeof process !== 'undefined' && process.env) {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n\n if (dbEmulatorHost) {\n isEmulator = true;\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\n repoInfo = parsedUrl.repoInfo;\n } else {\n isEmulator = !parsedUrl.repoInfo.secure;\n }\n\n const authTokenProvider =\n nodeAdmin && isEmulator\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\n\n validateUrl('Invalid Firebase Database URL', parsedUrl);\n if (!pathIsEmpty(parsedUrl.path)) {\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 = repoManagerCreateRepo(\n repoInfo,\n app,\n authTokenProvider,\n new AppCheckTokenProvider(app.name, appCheckProvider)\n );\n return new Database(repo, app);\n}\n\n/**\n * Remove the repo and make sure it is disconnected.\n *\n */\nfunction repoManagerDeleteRepo(repo: Repo, appName: string): void {\n const appRepos = repos[appName];\n // This should never happen...\n if (!appRepos || appRepos[repo.key] !== repo) {\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\n }\n repoInterrupt(repo);\n delete appRepos[repo.key];\n}\n\n/**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param repoInfo - The metadata about the Repo\n * @returns The Repo object for the specified server / repoName.\n */\nfunction repoManagerCreateRepo(\n repoInfo: RepoInfo,\n app: FirebaseApp,\n authTokenProvider: AuthTokenProvider,\n appCheckProvider: AppCheckTokenProvider\n): Repo {\n let appRepos = repos[app.name];\n\n if (!appRepos) {\n appRepos = {};\n repos[app.name] = appRepos;\n }\n\n let repo = 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, useRestClient, authTokenProvider, appCheckProvider);\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 */\nexport function repoManagerForceRestClient(forceRestClient: boolean): void {\n useRestClient = forceRestClient;\n}\n\n/**\n * Class representing a Firebase Realtime Database.\n */\nexport class Database implements _FirebaseService {\n /** Represents a `Database` instance. */\n readonly 'type' = 'database';\n\n /** Track if the instance has been used (root or repo accessed) */\n _instanceStarted: boolean = false;\n\n /** Backing state for root_ */\n private _rootInternal?: ReferenceImpl;\n\n /** @hideconstructor */\n constructor(\n public _repoInternal: Repo,\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\n readonly app: FirebaseApp\n ) {}\n\n get _repo(): Repo {\n if (!this._instanceStarted) {\n repoStart(\n this._repoInternal,\n this.app.options.appId,\n this.app.options['databaseAuthVariableOverride']\n );\n this._instanceStarted = true;\n }\n return this._repoInternal;\n }\n\n get _root(): ReferenceImpl {\n if (!this._rootInternal) {\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\n }\n return this._rootInternal;\n }\n\n _delete(): Promise<void> {\n if (this._rootInternal !== null) {\n repoManagerDeleteRepo(this._repo, this.app.name);\n this._repoInternal = null;\n this._rootInternal = null;\n }\n return Promise.resolve();\n }\n\n _checkNotDeleted(apiName: string) {\n if (this._rootInternal === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n}\n\nfunction checkTransportInit() {\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\n warn(\n 'Transport has already been initialized. Please call this function before calling ref or setting up a listener'\n );\n }\n}\n\n/**\n * Force the use of websockets instead of longPolling.\n */\nexport function forceWebSockets() {\n checkTransportInit();\n BrowserPollConnection.forceDisallow();\n}\n\n/**\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\n */\nexport function forceLongPolling() {\n checkTransportInit();\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n}\n\n/**\n * Returns the instance of the Realtime Database SDK that is associated\n * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with\n * with default settings if no instance exists or if the existing instance uses\n * a custom database URL.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\n * Database instance is associated with.\n * @param url - The URL of the Realtime Database instance to connect to. If not\n * provided, the SDK connects to the default instance of the Firebase App.\n * @returns The `Database` instance of the provided app.\n */\nexport function getDatabase(\n app: FirebaseApp = getApp(),\n url?: string\n): Database {\n const db = _getProvider(app, 'database').getImmediate({\n identifier: url\n }) as Database;\n if (!db._instanceStarted) {\n const emulator = getDefaultEmulatorHostnameAndPort('database');\n if (emulator) {\n connectDatabaseEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify the provided instance to communicate with the Realtime Database\n * emulator.\n *\n * <p>Note: This method must be called before performing any other operation.\n *\n * @param db - The instance to modify.\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\nexport function connectDatabaseEmulator(\n db: Database,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n db = getModularInstance(db);\n db._checkNotDeleted('useEmulator');\n if (db._instanceStarted) {\n fatal(\n 'Cannot call useEmulator() after instance has already been initialized.'\n );\n }\n\n const repo = db._repoInternal;\n let tokenProvider: EmulatorTokenProvider | undefined = undefined;\n if (repo.repoInfo_.nodeAdmin) {\n if (options.mockUserToken) {\n fatal(\n 'mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".'\n );\n }\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\n } else if (options.mockUserToken) {\n const token =\n typeof options.mockUserToken === 'string'\n ? options.mockUserToken\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\n tokenProvider = new EmulatorTokenProvider(token);\n }\n\n // Modify the repo to apply emulator settings\n repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\n}\n\n/**\n * Disconnects from the server (all Database operations will be completed\n * offline).\n *\n * The client automatically maintains a persistent connection to the Database\n * server, which will remain active indefinitely and reconnect when\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\n * to control the client connection in cases where a persistent connection is\n * undesirable.\n *\n * While offline, the client will no longer receive data updates from the\n * Database. However, all Database operations performed locally will continue to\n * immediately fire events, allowing your application to continue behaving\n * normally. Additionally, each operation performed locally will automatically\n * be queued and retried upon reconnection to the Database server.\n *\n * To reconnect to the Database and begin receiving remote events, see\n * `goOnline()`.\n *\n * @param db - The instance to disconnect.\n */\nexport function goOffline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOffline');\n repoInterrupt(db._repo);\n}\n\n/**\n * Reconnects to the server and synchronizes the offline Database state\n * with the server state.\n *\n * This method should be used after disabling the active connection with\n * `goOffline()`. Once reconnected, the client will transmit the proper data\n * and fire the appropriate events so that your client \"catches up\"\n * automatically.\n *\n * @param db - The instance to reconnect.\n */\nexport function goOnline(db: Database): void {\n db = getModularInstance(db);\n db._checkNotDeleted('goOnline');\n repoResume(db._repo);\n}\n\n/**\n * Logs debugging information to the console.\n *\n * @param enabled - Enables logging if `true`, disables logging if `false`.\n * @param persistent - Remembers the logging state between page refreshes if\n * `true`.\n */\nexport function enableLogging(enabled: boolean, persistent?: boolean);\n\n/**\n * Logs debugging information to the console.\n *\n * @param logger - A custom logger function to control how things get logged.\n */\nexport function enableLogging(logger: (message: string) => unknown);\n\nexport function enableLogging(\n logger: boolean | ((message: string) => unknown),\n persistent?: boolean\n): void {\n enableLoggingImpl(logger, persistent);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst SERVER_TIMESTAMP = {\n '.sv': 'timestamp'\n};\n\n/**\n * Returns a placeholder value for auto-populating the current timestamp (time\n * since the Unix epoch, in milliseconds) as determined by the Firebase\n * servers.\n */\nexport function serverTimestamp(): object {\n return SERVER_TIMESTAMP;\n}\n\n/**\n * Returns a placeholder value that can be used to atomically increment the\n * current database value by the provided delta.\n *\n * @param delta - the amount to modify the current value atomically.\n * @returns A placeholder value for modifying data atomically server-side.\n */\nexport function increment(delta: number): object {\n return {\n '.sv': {\n 'increment': delta\n }\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance, Deferred } from '@firebase/util';\n\nimport { repoStartTransaction } from '../core/Repo';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { Node } from '../core/snap/Node';\nimport { validateWritablePath } from '../core/util/validation';\n\nimport { DatabaseReference } from './Reference';\nimport { DataSnapshot, onValue, ReferenceImpl } from './Reference_impl';\n\n/** An options object to configure transactions. */\nexport interface TransactionOptions {\n /**\n * By default, events are raised each time the transaction update function\n * runs. So if it is run multiple times, you may see intermediate states. You\n * can set this to false to suppress these intermediate states and instead\n * wait until the transaction has completed before events are raised.\n */\n readonly applyLocally?: boolean;\n}\n\n/**\n * A type for the resolve value of {@link runTransaction}.\n */\nexport class TransactionResult {\n /** @hideconstructor */\n constructor(\n /** Whether the transaction was successfully committed. */\n readonly committed: boolean,\n /** The resulting data snapshot. */\n readonly snapshot: DataSnapshot\n ) {}\n\n /** Returns a JSON-serializable representation of this object. */\n toJSON(): object {\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n\n/**\n * Atomically modifies the data at this location.\n *\n * Atomically modify the data at this location. Unlike a normal `set()`, which\n * just overwrites the data regardless of its previous value, `runTransaction()` is\n * used to modify the existing value to a new value, ensuring there are no\n * conflicts with other clients writing to the same location at the same time.\n *\n * To accomplish this, you pass `runTransaction()` an update function which is\n * used to transform the current value into a new value. If another client\n * writes to the location before your new value is successfully written, your\n * update function will be called again with the new current value, and the\n * write will be retried. This will happen repeatedly until your write succeeds\n * without conflict or you abort the transaction by not returning a value from\n * your update function.\n *\n * Note: Modifying data with `set()` will cancel any pending transactions at\n * that location, so extreme care should be taken if mixing `set()` and\n * `runTransaction()` to update the same data.\n *\n * Note: When using transactions with Security and Firebase Rules in place, be\n * aware that a client needs `.read` access in addition to `.write` access in\n * order to perform a transaction. This is because the client-side nature of\n * transactions requires the client to read the data in order to transactionally\n * update it.\n *\n * @param ref - The location to atomically modify.\n * @param transactionUpdate - A developer-supplied function which will be passed\n * the current data stored at this location (as a JavaScript object). The\n * function should return the new value it would like written (as a JavaScript\n * object). If `undefined` is returned (i.e. you return with no arguments) the\n * transaction will be aborted and the data at this location will not be\n * modified.\n * @param options - An options object to configure transactions.\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\n * callback to handle success and failure.\n */\nexport function runTransaction(\n ref: DatabaseReference,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transactionUpdate: (currentData: any) => unknown,\n options?: TransactionOptions\n): Promise<TransactionResult> {\n ref = getModularInstance(ref);\n\n validateWritablePath('Reference.transaction', ref._path);\n\n if (ref.key === '.length' || ref.key === '.keys') {\n throw (\n 'Reference.transaction failed: ' + ref.key + ' is a read-only object.'\n );\n }\n\n const applyLocally = options?.applyLocally ?? true;\n const deferred = new Deferred<TransactionResult>();\n\n const promiseComplete = (\n error: Error | null,\n committed: boolean,\n node: Node | null\n ) => {\n let dataSnapshot: DataSnapshot | null = null;\n if (error) {\n deferred.reject(error);\n } else {\n dataSnapshot = new DataSnapshot(\n node,\n new ReferenceImpl(ref._repo, ref._path),\n PRIORITY_INDEX\n );\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\n }\n };\n\n // Add a watch to make sure we get server updates.\n const unwatcher = onValue(ref, () => {});\n\n repoStartTransaction(\n ref._repo,\n ref._path,\n transactionUpdate,\n promiseComplete,\n unwatcher,\n applyLocally\n );\n\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PersistentConnection } from '../core/PersistentConnection';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { Connection } from '../realtime/Connection';\n\nimport { repoManagerForceRestClient } from './Database';\n\nexport const DataConnection = PersistentConnection;\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// 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 * @internal\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\nexport const ConnectionTarget = RepoInfo;\n\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n * @internal\n */\nexport const forceRestClient = function (forceRestClient: boolean) {\n repoManagerForceRestClient(forceRestClient);\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nconst logClient = new Logger('@firebase/database-compat');\n\nexport const warn = function (msg: string) {\n const message = 'FIREBASE WARNING: ' + msg;\n logClient.warn(message);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnDisconnect as ModularOnDisconnect } from '@firebase/database';\nimport { validateArgCount, validateCallback, Compat } from '@firebase/util';\n\nimport { warn } from '../util/util';\nexport class OnDisconnect implements Compat<ModularOnDisconnect> {\n constructor(readonly _delegate: ModularOnDisconnect) {}\n\n cancel(onComplete?: (a: Error | null) => void): Promise<void> {\n validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n validateCallback('OnDisconnect.cancel', 'onComplete', onComplete, true);\n const result = this._delegate.cancel();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise<void> {\n validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validateCallback('OnDisconnect.remove', 'onComplete', onComplete, true);\n const result = this._delegate.remove();\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n set(value: unknown, onComplete?: (a: Error | null) => void): Promise<void> {\n validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validateCallback('OnDisconnect.set', 'onComplete', onComplete, true);\n const result = this._delegate.set(value);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\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 validateCallback(\n 'OnDisconnect.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n const result = this._delegate.setWithPriority(value, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n objectToMerge: Record<string, unknown>,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\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 validateCallback('OnDisconnect.update', 'onComplete', onComplete, true);\n const result = this._delegate.update(objectToMerge);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateArgCount } from '@firebase/util';\n\nimport { DataSnapshot } from './Reference';\n\nexport class TransactionResult {\n /**\n * A type for the resolve value of Firebase.transaction.\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n OnDisconnect as ModularOnDisconnect,\n off,\n onChildAdded,\n onChildChanged,\n onChildMoved,\n onChildRemoved,\n onValue,\n EventType,\n limitToFirst,\n query,\n limitToLast,\n orderByChild,\n orderByKey,\n orderByValue,\n orderByPriority,\n startAt,\n startAfter,\n endAt,\n endBefore,\n equalTo,\n get,\n set,\n update,\n setWithPriority,\n remove,\n setPriority,\n push,\n runTransaction,\n child,\n DataSnapshot as ModularDataSnapshot,\n Query as ExpQuery,\n DatabaseReference as ModularReference,\n _QueryImpl,\n _ReferenceImpl,\n _validatePathString,\n _validateWritablePath,\n _UserCallback,\n _QueryParams\n} from '@firebase/database';\nimport {\n Compat,\n Deferred,\n errorPrefix,\n validateArgCount,\n validateCallback,\n validateContextObject\n} from '@firebase/util';\n\nimport { warn } from '../util/util';\nimport { validateBoolean, validateEventType } from '../util/validation';\n\nimport { Database } from './Database';\nimport { OnDisconnect } from './onDisconnect';\nimport { TransactionResult } from './TransactionResult';\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 implements Compat<ModularDataSnapshot> {\n constructor(\n readonly _database: Database,\n readonly _delegate: ModularDataSnapshot\n ) {}\n\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @returns 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._delegate.val();\n }\n\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @returns 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._delegate.exportVal();\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._delegate.toJSON();\n }\n\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @returns 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._delegate.exists();\n }\n\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param path - Path to a child.\n * @returns DataSnapshot for child node.\n */\n child(path: string): DataSnapshot {\n validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n path = String(path);\n _validatePathString('DataSnapshot.child', 'path', path, false);\n return new DataSnapshot(this._database, this._delegate.child(path));\n }\n\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param path - Path to a child.\n * @returns Whether the child exists.\n */\n hasChild(path: string): boolean {\n validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n _validatePathString('DataSnapshot.hasChild', 'path', path, false);\n return this._delegate.hasChild(path);\n }\n\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @returns The priority.\n */\n getPriority(): string | number | null {\n validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n return this._delegate.priority;\n }\n\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param action - Callback function to be called\n * for each child.\n * @returns True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n forEach(action: (snapshot: IteratedDataSnapshot) => boolean | void): boolean {\n validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n validateCallback('DataSnapshot.forEach', 'action', action, false);\n return this._delegate.forEach(expDataSnapshot =>\n action(new DataSnapshot(this._database, expDataSnapshot))\n );\n }\n\n /**\n * Returns whether this DataSnapshot has children.\n * @returns True if the DataSnapshot contains 1 or more child nodes.\n */\n hasChildren(): boolean {\n validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n return this._delegate.hasChildren();\n }\n\n get key() {\n return this._delegate.key;\n }\n\n /**\n * Returns the number of children for this DataSnapshot.\n * @returns The number of children that this DataSnapshot contains.\n */\n numChildren(): number {\n validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this._delegate.size;\n }\n\n /**\n * @returns The Firebase reference for the location this snapshot's data came\n * from.\n */\n getRef(): Reference {\n validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return new Reference(this._database, this._delegate.ref);\n }\n\n get ref(): Reference {\n return this.getRef();\n }\n}\n\n/**\n * Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.\n */\nexport interface IteratedDataSnapshot extends DataSnapshot {\n key: string; // key of the location of this snapshot.\n}\n\nexport interface SnapshotCallback {\n (dataSnapshot: DataSnapshot, previousChildName?: 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 implements Compat<ExpQuery> {\n constructor(readonly database: Database, readonly _delegate: ExpQuery) {}\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 validateCallback('Query.on', 'callback', callback, false);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.on',\n cancelCallbackOrContext,\n context\n );\n const valueCallback = (expSnapshot, previousChildName?) => {\n callback.call(\n ret.context,\n new DataSnapshot(this.database, expSnapshot),\n previousChildName\n );\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = ret.cancel?.bind(ret.context);\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback);\n return callback;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback);\n return callback;\n default:\n throw new Error(\n errorPrefix('Query.on', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n }\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', eventType, true);\n validateCallback('Query.off', 'callback', callback, true);\n validateContextObject('Query.off', 'context', context, true);\n if (callback) {\n const valueCallback: _UserCallback = () => {};\n valueCallback.userCallback = callback;\n valueCallback.context = context;\n off(this._delegate, eventType as EventType, valueCallback);\n } else {\n off(this._delegate, eventType as EventType | undefined);\n }\n }\n\n /**\n * Get the server-value for this query, or return a cached value if not connected.\n */\n get(): Promise<DataSnapshot> {\n return get(this._delegate).then(expSnapshot => {\n return new DataSnapshot(this.database, expSnapshot);\n });\n }\n\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n */\n once(\n eventType: string,\n callback?: SnapshotCallback,\n failureCallbackOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): Promise<DataSnapshot> {\n validateArgCount('Query.once', 1, 4, arguments.length);\n validateCallback('Query.once', 'callback', callback, true);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.once',\n failureCallbackOrContext,\n context\n );\n const deferred = new Deferred<DataSnapshot>();\n const valueCallback: _UserCallback = (expSnapshot, previousChildName?) => {\n const result = new DataSnapshot(this.database, expSnapshot);\n if (callback) {\n callback.call(ret.context, result, previousChildName);\n }\n deferred.resolve(result);\n };\n valueCallback.userCallback = callback;\n valueCallback.context = ret.context;\n const cancelCallback = (error: Error) => {\n if (ret.cancel) {\n ret.cancel.call(ret.context, error);\n }\n deferred.reject(error);\n };\n\n switch (eventType) {\n case 'value':\n onValue(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_added':\n onChildAdded(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_removed':\n onChildRemoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_changed':\n onChildChanged(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n case 'child_moved':\n onChildMoved(this._delegate, valueCallback, cancelCallback, {\n onlyOnce: true\n });\n break;\n default:\n throw new Error(\n errorPrefix('Query.once', 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n\n return deferred.promise;\n }\n\n /**\n * Set a limit and anchor it to the start of the window.\n */\n limitToFirst(limit: number): Query {\n validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToFirst(limit)));\n }\n\n /**\n * Set a limit and anchor it to the end of the window.\n */\n limitToLast(limit: number): Query {\n validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, limitToLast(limit)));\n }\n\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n */\n orderByChild(path: string): Query {\n validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n return new Query(this.database, query(this._delegate, orderByChild(path)));\n }\n\n /**\n * Return a new query ordered by the KeyIndex\n */\n orderByKey(): Query {\n validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByKey()));\n }\n\n /**\n * Return a new query ordered by the PriorityIndex\n */\n orderByPriority(): Query {\n validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByPriority()));\n }\n\n /**\n * Return a new query ordered by the ValueIndex\n */\n orderByValue(): Query {\n validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n return new Query(this.database, query(this._delegate, orderByValue()));\n }\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 return new Query(\n this.database,\n query(this._delegate, startAt(value, name))\n );\n }\n\n startAfter(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAfter', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, startAfter(value, name))\n );\n }\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 return new Query(this.database, query(this._delegate, endAt(value, name)));\n }\n\n endBefore(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endBefore', 0, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, endBefore(value, name))\n );\n }\n\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n */\n equalTo(value: number | string | boolean | null, name?: string) {\n validateArgCount('Query.equalTo', 1, 2, arguments.length);\n return new Query(\n this.database,\n query(this._delegate, equalTo(value, name))\n );\n }\n\n /**\n * @returns URL for this location.\n */\n toString(): string {\n validateArgCount('Query.toString', 0, 0, arguments.length);\n return this._delegate.toString();\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._delegate.toJSON();\n }\n\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\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 return this._delegate.isEqual(other._delegate);\n }\n\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param fnName - The function name (on or once)\n *\n */\n private static getCancelAndContextArgs_(\n fnName: string,\n cancelOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): { cancel: ((a: Error) => void) | undefined; context: object | undefined } {\n const ret: {\n cancel: ((a: Error) => void) | null;\n context: object | null;\n } = { cancel: undefined, context: undefined };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext as (a: Error) => void;\n validateCallback(fnName, 'cancel', ret.cancel, true);\n\n ret.context = context;\n validateContextObject(fnName, 'context', 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, 'cancelOrContext') +\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 new Reference(\n this.database,\n new _ReferenceImpl(this._delegate._repo, this._delegate._path)\n );\n }\n}\n\nexport class Reference extends Query implements Compat<ModularReference> {\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 constructor(\n readonly database: Database,\n readonly _delegate: ModularReference\n ) {\n super(\n database,\n new _QueryImpl(\n _delegate._repo,\n _delegate._path,\n new _QueryParams(),\n false\n )\n );\n }\n\n /** @returns {?string} */\n getKey(): string | null {\n validateArgCount('Reference.key', 0, 0, arguments.length);\n return this._delegate.key;\n }\n\n child(pathString: string): Reference {\n validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n return new Reference(this.database, child(this._delegate, pathString));\n }\n\n /** @returns {?Reference} */\n getParent(): Reference | null {\n validateArgCount('Reference.parent', 0, 0, arguments.length);\n const parent = this._delegate.parent;\n return parent ? new Reference(this.database, parent) : null;\n }\n\n /** @returns {!Reference} */\n getRoot(): Reference {\n validateArgCount('Reference.root', 0, 0, arguments.length);\n return new Reference(this.database, this._delegate.root);\n }\n\n set(\n newVal: unknown,\n onComplete?: (error: Error | null) => void\n ): Promise<void> {\n validateArgCount('Reference.set', 1, 2, arguments.length);\n validateCallback('Reference.set', 'onComplete', onComplete, true);\n const result = set(this._delegate, newVal);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n update(\n values: object,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('Reference.update', 1, 2, arguments.length);\n\n if (Array.isArray(values)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\n for (let i = 0; i < values.length; ++i) {\n newObjectToMerge['' + i] = values[i];\n }\n values = 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 _validateWritablePath('Reference.update', this._delegate._path);\n validateCallback('Reference.update', 'onComplete', onComplete, true);\n\n const result = update(this._delegate, values);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n setWithPriority(\n newVal: unknown,\n newPriority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validateCallback(\n 'Reference.setWithPriority',\n 'onComplete',\n onComplete,\n true\n );\n\n const result = setWithPriority(this._delegate, newVal, newPriority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n remove(onComplete?: (a: Error | null) => void): Promise<void> {\n validateArgCount('Reference.remove', 0, 1, arguments.length);\n validateCallback('Reference.remove', 'onComplete', onComplete, true);\n\n const result = remove(this._delegate);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n transaction(\n transactionUpdate: (currentData: unknown) => unknown,\n onComplete?: (\n error: Error | null,\n committed: boolean,\n dataSnapshot: DataSnapshot | null\n ) => void,\n applyLocally?: boolean\n ): Promise<TransactionResult> {\n validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validateCallback(\n 'Reference.transaction',\n 'transactionUpdate',\n transactionUpdate,\n false\n );\n validateCallback('Reference.transaction', 'onComplete', onComplete, true);\n validateBoolean(\n 'Reference.transaction',\n 'applyLocally',\n applyLocally,\n true\n );\n\n const result = runTransaction(this._delegate, transactionUpdate, {\n applyLocally\n }).then(\n transactionResult =>\n new TransactionResult(\n transactionResult.committed,\n new DataSnapshot(this.database, transactionResult.snapshot)\n )\n );\n if (onComplete) {\n result.then(\n transactionResult =>\n onComplete(\n null,\n transactionResult.committed,\n transactionResult.snapshot\n ),\n error => onComplete(error, false, null)\n );\n }\n return result;\n }\n\n setPriority(\n priority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validateCallback('Reference.setPriority', 'onComplete', onComplete, true);\n\n const result = setPriority(this._delegate, priority);\n if (onComplete) {\n result.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n return result;\n }\n\n push(value?: unknown, onComplete?: (a: Error | null) => void): Reference {\n validateArgCount('Reference.push', 0, 2, arguments.length);\n validateCallback('Reference.push', 'onComplete', onComplete, true);\n\n const expPromise = push(this._delegate, value);\n const promise = expPromise.then(\n expRef => new Reference(this.database, expRef)\n );\n\n if (onComplete) {\n promise.then(\n () => onComplete(null),\n error => onComplete(error)\n );\n }\n\n const result = new Reference(this.database, expPromise);\n result.then = promise.then.bind(promise);\n result.catch = promise.catch.bind(promise, undefined);\n return result;\n }\n\n onDisconnect(): OnDisconnect {\n _validateWritablePath('Reference.onDisconnect', this._delegate._path);\n return new OnDisconnect(\n new ModularOnDisconnect(this._delegate._repo, this._delegate._path)\n );\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 * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorPrefix as errorPrefixFxn } from '@firebase/util';\n\nexport const validateBoolean = function (\n fnName: string,\n argumentName: string,\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, argumentName) + 'must be a boolean.'\n );\n }\n};\n\nexport const validateEventType = function (\n fnName: string,\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, 'eventType') +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport {\n forceLongPolling,\n forceWebSockets,\n goOnline,\n connectDatabaseEmulator,\n goOffline,\n ref,\n refFromURL,\n increment,\n serverTimestamp,\n Database as ModularDatabase\n} from '@firebase/database';\nimport {\n validateArgCount,\n Compat,\n EmulatorMockTokenOptions\n} from '@firebase/util';\n\nimport { Reference } from './Reference';\n\n/**\n * Class representing a firebase database.\n */\nexport class Database implements FirebaseService, Compat<ModularDatabase> {\n static readonly ServerValue = {\n TIMESTAMP: serverTimestamp(),\n increment: (delta: number) => increment(delta)\n };\n\n /**\n * The constructor should not be called by users of our public API.\n */\n constructor(readonly _delegate: ModularDatabase, readonly app: FirebaseApp) {}\n\n INTERNAL = {\n delete: () => this._delegate._delete(),\n forceWebSockets,\n forceLongPolling\n };\n\n /**\n * Modify this instance to communicate with the Realtime Database emulator.\n *\n * <p>Note: This method must be called before performing any other operation.\n *\n * @param host - the emulator host (ex: localhost)\n * @param port - the emulator port (ex: 8080)\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\n */\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions;\n } = {}\n ): void {\n connectDatabaseEmulator(this._delegate, host, port, options);\n }\n\n /**\n * Returns a reference to the root or to the path specified in the provided\n * argument.\n *\n * @param path - The relative string path or an existing Reference to a database\n * location.\n * @throws If a Reference is provided, throws if it does not belong to the\n * same project.\n * @returns Firebase reference.\n */\n ref(path?: string): Reference;\n ref(path?: Reference): Reference;\n ref(path?: string | Reference): Reference {\n validateArgCount('database.ref', 0, 1, arguments.length);\n if (path instanceof Reference) {\n const childRef = refFromURL(this._delegate, path.toString());\n return new Reference(this, childRef);\n } else {\n const childRef = ref(this._delegate, path);\n return new Reference(this, childRef);\n }\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 * @returns Firebase reference.\n */\n refFromURL(url: string): Reference {\n const apiName = 'database.refFromURL';\n validateArgCount(apiName, 1, 1, arguments.length);\n const childRef = refFromURL(this._delegate, url);\n return new Reference(this, childRef);\n }\n\n // Make individual repo go offline.\n goOffline(): void {\n validateArgCount('database.goOffline', 0, 0, arguments.length);\n return goOffline(this._delegate);\n }\n\n goOnline(): void {\n validateArgCount('database.goOnline', 0, 0, arguments.length);\n return goOnline(this._delegate);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase, { FirebaseNamespace } from '@firebase/app-compat';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport { enableLogging } from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { name, version } from '../package.json';\nimport { Database } from '../src/api/Database';\nimport * as INTERNAL from '../src/api/internal';\nimport { DataSnapshot, Query, Reference } from '../src/api/Reference';\n\nconst ServerValue = Database.ServerValue;\n\nexport function registerDatabase(instance: FirebaseNamespace) {\n // Register the Database Service with the 'firebase' namespace.\n (instance as unknown as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'database-compat',\n (container, { instanceIdentifier: url }) => {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app-compat').getImmediate();\n const databaseExp = container\n .getProvider('database')\n .getImmediate({ identifier: url });\n return new Database(databaseExp, app);\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 }\n )\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterDatabase(firebase);\n\ndeclare module '@firebase/app-compat' {\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","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n AppCheckInternalComponentName,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { FirebaseApp } from '@firebase/app-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n Provider\n} from '@firebase/component';\nimport {\n _repoManagerDatabaseFromApp,\n _setSDKVersion\n} from '@firebase/database';\nimport * as types from '@firebase/database-types';\n\nimport { Database } from './Database';\n\n/**\n * Used by console to create a database based on the app,\n * passed database URL and a custom auth implementation.\n *\n * @param app - A valid FirebaseApp-like object\n * @param url - A valid Firebase databaseURL\n * @param version - custom version e.g. firebase-admin version\n * @param customAuthImpl - custom auth implementation\n */\nexport function initStandalone<T>({\n app,\n url,\n version,\n customAuthImpl,\n customAppCheckImpl,\n namespace,\n nodeAdmin = false\n}: {\n app: FirebaseApp;\n url: string;\n version: string;\n customAuthImpl: FirebaseAuthInternal;\n customAppCheckImpl?: FirebaseAppCheckInternal;\n namespace: T;\n nodeAdmin?: boolean;\n}): {\n instance: types.Database;\n namespace: T;\n} {\n _setSDKVersion(version);\n\n const container = new ComponentContainer('database-standalone');\n /**\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\n * any actual function.\n */\n const authProvider = new Provider<FirebaseAuthInternalName>(\n 'auth-internal',\n container\n );\n authProvider.setComponent(\n new Component('auth-internal', () => customAuthImpl, ComponentType.PRIVATE)\n );\n\n let appCheckProvider: Provider<AppCheckInternalComponentName> = undefined;\n if (customAppCheckImpl) {\n appCheckProvider = new Provider<AppCheckInternalComponentName>(\n 'app-check-internal',\n container\n );\n appCheckProvider.setComponent(\n new Component(\n 'app-check-internal',\n () => customAppCheckImpl,\n ComponentType.PRIVATE\n )\n );\n }\n\n return {\n instance: new Database(\n _repoManagerDatabaseFromApp(\n app,\n authProvider,\n appCheckProvider,\n url,\n nodeAdmin\n ),\n app\n ) as types.Database,\n namespace\n };\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Bootstrap for the Google JS Library (Closure).\n *\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\n * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects\n * to include their own deps file(s) from different locations.\n *\n * Avoid including base.js more than once. This is strictly discouraged and not\n * supported. goog.require(...) won't work properly in that case.\n *\n * @suppress {deprecated} Users cannot remove deprecated uses here.\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 * Currently the Closure Compiler will only recognize very simple definitions of\n * this value when looking for values to apply to compiled code and ignore all\n * other references. Specifically, it looks the value defined at the variable\n * declaration, as with the example above.\n *\n * TODO(user): Improve the recognized definitions.\n *\n * @type {!Object<string, (string|number|boolean)>|null|undefined}\n */\ngoog.global.CLOSURE_DEFINES;\n\n\n/**\n * Builds an object structure for the provided namespace path, ensuring that\n * names that already exist are not overwritten. For example:\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\n * Used by goog.provide and goog.exportSymbol.\n * @param {string} name The name of the object that this file defines.\n * @param {*=} object The object to expose at the end of the path.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether object should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @param {?Object=} objectToExportTo The object to add the path to; if this\n * field is not specified, its value defaults to `goog.global`.\n * @private\n */\ngoog.exportPath_ = function(name, object, overwriteImplicit, objectToExportTo) {\n var parts = name.split('.');\n var cur = 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 && object !== undefined) {\n if (!overwriteImplicit && goog.isObject(object) &&\n goog.isObject(cur[part])) {\n // Merge properties on object (the input parameter) with the existing\n // implicitly defined namespace, so as to not clobber previously\n // defined child namespaces.\n for (var prop in object) {\n if (object.hasOwnProperty(prop)) {\n cur[part][prop] = object[prop];\n }\n }\n } else {\n // Either there is no existing implicit namespace, or overwriteImplicit\n // is set to true, so directly assign object (the input parameter) to\n // the namespace.\n cur[part] = object;\n }\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 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 * deprecated Use goog.module (see b/159289405)\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=} object The object to embed in the namespace.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether opt_obj should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @private\n */\ngoog.constructNamespace_ = function(name, object, overwriteImplicit) {\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, object, overwriteImplicit);\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 * 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 * @private\n */\ngoog.getScriptNonce_ = function(opt_window) {\n var doc = (opt_window || goog.global).document;\n var script = doc.querySelector && doc.querySelector('script[nonce]');\n if (script) {\n // Try to get the nonce from the IDL property first, because browsers that\n // implement additional nonce protection features (currently only Chrome) to\n // prevent nonce stealing via CSS do not expose the nonce via attributes.\n // See https://github.com/whatwg/html/issues/2369\n var nonce = script['nonce'] || script.getAttribute('nonce');\n if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\n return nonce;\n }\n }\n return '';\n};\n\n\n/**\n * Module identifier validation regexp.\n * Note: This is a conservative check, it is very possible to be more lenient,\n * the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\n * restrictions are intended to leave the door open for using goog.require\n * with relative file paths rather than module identifiers.\n * @private\n */\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\n\n\n/**\n * Defines a module in Closure.\n *\n * Marks that this file must be loaded as a module and claims the namespace.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * goog.module() has three requirements:\n * - goog.module may not be used in the same file as goog.provide.\n * - goog.module must be the first statement in the file.\n * - only one goog.module is allowed per file.\n *\n * When a goog.module annotated file is loaded, it is enclosed in\n * a strict function closure. This means that:\n * - any variables declared in a goog.module file are private to the file\n * (not global), though the compiler is expected to inline the module.\n * - The code must obey all the rules of \"strict\" JavaScript.\n * - the file will be marked as \"use strict\"\n *\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\n * itself. If declared symbols are desired, use\n * goog.module.declareLegacyNamespace().\n *\n *\n * See the public goog.module proposal: http://goo.gl/Va1hin\n *\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\", is expected but not required.\n * @return {void}\n */\ngoog.module = function(name) {\n if (typeof name !== 'string' || !name ||\n name.search(goog.VALID_MODULE_RE_) == -1) {\n throw new Error('Invalid module identifier');\n }\n if (!goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'Module ' + name + ' has been loaded incorrectly. Note, ' +\n 'modules cannot be loaded as normal scripts. They require some kind of ' +\n 'pre-processing step. You\\'re likely trying to load a module via a ' +\n 'script tag or as a part of a concatenated bundle without rewriting the ' +\n 'module. For more info see: ' +\n 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\n }\n if (goog.moduleLoaderState_.moduleName) {\n throw new Error('goog.module may only be called once per module.');\n }\n\n // Store the module name for the loader.\n goog.moduleLoaderState_.moduleName = name;\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n delete goog.implicitNamespaces_[name];\n }\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n *\n * Note: This is not an alternative to goog.require, it does not\n * indicate a hard dependency, instead it is used to indicate\n * an optional dependency or to access the exports of a module\n * that has already been loaded.\n * @suppress {missingProvide}\n */\ngoog.module.get = function(name) {\n return goog.module.getInternal_(name);\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n * @private\n */\ngoog.module.getInternal_ = function(name) {\n if (!COMPILED) {\n if (name in goog.loadedModules_) {\n return goog.loadedModules_[name].exports;\n } else if (!goog.implicitNamespaces_[name]) {\n var ns = goog.getObjectByName(name);\n return ns != null ? ns : null;\n }\n }\n return null;\n};\n\n/**\n * Types of modules the debug loader can load.\n * @enum {string}\n */\ngoog.ModuleType = {\n ES6: 'es6',\n GOOG: 'goog'\n};\n\n\n/**\n * @private {?{\n * moduleName: (string|undefined),\n * declareLegacyNamespace:boolean,\n * type: ?goog.ModuleType\n * }}\n */\ngoog.moduleLoaderState_ = null;\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module or an es6 module is currently being\n * initialized.\n */\ngoog.isInModuleLoader_ = function() {\n return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\n};\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module is currently being initialized.\n */\ngoog.isInGoogModuleLoader_ = function() {\n return !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\n};\n\n\n/**\n * @private\n * @return {boolean} Whether an es6 module is currently being initialized.\n */\ngoog.isInEs6ModuleLoader_ = function() {\n var inLoader = !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.ES6;\n\n if (inLoader) {\n return true;\n }\n\n var jscomp = goog.global['$jscomp'];\n\n if (jscomp) {\n // jscomp may not have getCurrentModulePath if this is a compiled bundle\n // that has some of the runtime, but not all of it. This can happen if\n // optimizations are turned on so the unused runtime is removed but renaming\n // and Closure pass are off (so $jscomp is still named $jscomp and the\n // goog.provide/require calls still exist).\n if (typeof jscomp.getCurrentModulePath != 'function') {\n return false;\n }\n\n // Bundled ES6 module.\n return !!jscomp.getCurrentModulePath();\n }\n\n return false;\n};\n\n\n/**\n * Provide the module's exports as a globally accessible object under the\n * module's declared name. This is intended to ease migration to goog.module\n * for files that have existing usages.\n * @suppress {missingProvide}\n */\ngoog.module.declareLegacyNamespace = function() {\n if (!COMPILED && !goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'goog.module.declareLegacyNamespace must be called from ' +\n 'within a goog.module');\n }\n if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.module must be called prior to ' +\n 'goog.module.declareLegacyNamespace.');\n }\n goog.moduleLoaderState_.declareLegacyNamespace = true;\n};\n\n\n/**\n * Associates an ES6 module with a Closure module ID so that is available via\n * goog.require. The associated ID acts like a goog.module ID - it does not\n * create any global names, it is merely available via goog.require /\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\n * goog.module.get will return the entire module as if it was import *'d. This\n * allows Closure files to reference ES6 modules for the sake of migration.\n *\n * @param {string} namespace\n * @suppress {missingProvide}\n */\ngoog.declareModuleId = function(namespace) {\n if (!COMPILED) {\n if (!goog.isInEs6ModuleLoader_()) {\n throw new Error(\n 'goog.declareModuleId may only be called from ' +\n 'within an ES6 module');\n }\n if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.declareModuleId may only be called once per module.');\n }\n if (namespace in goog.loadedModules_) {\n throw new Error(\n 'Module with namespace \"' + namespace + '\" already exists.');\n }\n }\n if (goog.moduleLoaderState_) {\n // Not bundled - debug loading.\n goog.moduleLoaderState_.moduleName = namespace;\n } else {\n // Bundled - not debug loading, no module loader state.\n var jscomp = goog.global['$jscomp'];\n if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\n throw new Error(\n 'Module with namespace \"' + namespace +\n '\" has been loaded incorrectly.');\n }\n var exports = jscomp.require(jscomp.getCurrentModulePath());\n goog.loadedModules_[namespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: namespace\n };\n }\n};\n\n\n/**\n * Marks that the current file should only be used for testing, and never for\n * live code in production.\n *\n * In the case of unit tests, the message may optionally be an exact namespace\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\n * provide (if not explicitly defined in the code).\n *\n * @param {string=} opt_message Optional message to add to the error that's\n * raised when used in production code.\n */\ngoog.setTestOnly = function(opt_message) {\n if (goog.DISALLOW_TEST_ONLY_CODE) {\n opt_message = opt_message || '';\n throw new Error(\n 'Importing test-only code into non-debug environment' +\n (opt_message ? ': ' + opt_message : '.'));\n }\n};\n\n\n/**\n * Forward declares a symbol. This is an indication to the compiler that the\n * symbol may be used in the source yet is not required and may not be provided\n * in compilation.\n *\n * The most common usage of forward declaration is code that takes a type as a\n * function parameter but does not need to require it. By forward declaring\n * instead of requiring, no hard dependency is made, and (if not required\n * elsewhere) the namespace may never be required and thus, not be pulled\n * into the JavaScript binary. If it is required elsewhere, it will be type\n * checked as normal.\n *\n * Before using goog.forwardDeclare, please read the documentation at\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\n * understand the options and tradeoffs when working with forward declarations.\n *\n * @param {string} name The namespace to forward declare in the form of\n * \"goog.package.part\".\n * @deprecated See go/noforwarddeclaration, Use `goog.requireType` instead.\n */\ngoog.forwardDeclare = function(name) {};\n\n\n/**\n * Forward declare type information. Used to assign types to goog.global\n * referenced object that would otherwise result in unknown type references\n * and thus block property disambiguation.\n */\ngoog.forwardDeclare('Document');\ngoog.forwardDeclare('HTMLScriptElement');\ngoog.forwardDeclare('XMLHttpRequest');\n\n\nif (!COMPILED) {\n /**\n * Check if the given name has been goog.provided. This will return false for\n * names that are available only as implicit namespaces.\n * @param {string} name name of the object to look for.\n * @return {boolean} Whether the name has been provided.\n * @private\n */\n goog.isProvided_ = function(name) {\n return (name in goog.loadedModules_) ||\n (!goog.implicitNamespaces_[name] && goog.getObjectByName(name) != null);\n };\n\n /**\n * Namespaces implicitly defined by goog.provide. For example,\n * goog.provide('goog.events.Event') implicitly declares that 'goog' and\n * 'goog.events' must be namespaces.\n *\n * @type {!Object<string, (boolean|undefined)>}\n * @private\n */\n goog.implicitNamespaces_ = {'goog.module': true};\n\n // NOTE: We add goog.module as an implicit namespace as goog.module is defined\n // here and because the existing module package has not been moved yet out of\n // the goog.module namespace. This satisifies both the debug loader and\n // ahead-of-time dependency management.\n}\n\n\n/**\n * Returns an object based on its fully qualified external name. The object\n * is not found if null or undefined. If you are using a compilation pass that\n * renames property names beware that using this function will not find renamed\n * properties.\n *\n * @param {string} name The fully qualified name.\n * @param {Object=} opt_obj The object within which to look; default is\n * |goog.global|.\n * @return {?} The value (object or primitive) or, if not found, null.\n */\ngoog.getObjectByName = function(name, opt_obj) {\n var parts = name.split('.');\n var cur = opt_obj || goog.global;\n for (var i = 0; i < parts.length; i++) {\n cur = cur[parts[i]];\n if (cur == null) {\n return null;\n }\n }\n return cur;\n};\n\n\n/**\n * Adds a dependency from a file to the files it requires.\n * @param {string} relPath The path to the js file.\n * @param {!Array<string>} provides An array of strings with\n * the names of the objects this file provides.\n * @param {!Array<string>} requires An array of strings with\n * the names of the objects this file requires.\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\n * how the file must be loaded. The boolean 'true' is equivalent\n * to {'module': 'goog'} for backwards-compatibility. Valid properties\n * and values include {'module': 'goog'} and {'lang': 'es6'}.\n */\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\n if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\n }\n};\n\n\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\n// to do \"debug-mode\" development. The dependency system can sometimes be\n// confusing, as can the debug DOM loader's asynchronous nature.\n//\n// With the DOM loader, a call to goog.require() is not blocking -- the script\n// will not load until some point after the current script. If a namespace is\n// needed at runtime, it needs to be defined in a previous script, or loaded via\n// require() with its registered dependencies.\n//\n// User-defined namespaces may need their own deps file. For a reference on\n// creating a deps file, see:\n// Externally: https://developers.google.com/closure/library/docs/depswriter\n//\n// Because of legacy clients, the DOM loader can't be easily removed from\n// base.js. Work was done to make it disableable or replaceable for\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\n// for example). See bootstrap/ for more information.\n\n\n/**\n * @define {boolean} Whether to enable the debug loader.\n *\n * If enabled, a call to goog.require() will attempt to load the namespace by\n * appending a script tag to the DOM (if the namespace has been registered).\n *\n * If disabled, goog.require() will simply assert that the namespace has been\n * provided (and depend on the fact that some outside tool correctly ordered\n * the script).\n */\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', false);\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 * When defining a class Foo with an abstract method bar(), you can do:\n * Foo.prototype.bar = goog.abstractMethod\n *\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\n * when bar() is invoked.\n *\n * @type {!Function}\n * @throws {Error} when invoked to indicate the method should be overridden.\n * @deprecated Use \"@abstract\" annotation instead of goog.abstractMethod in new\n * code. See\n * https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods\n */\ngoog.abstractMethod = function() {\n throw new Error('unimplemented abstract method');\n};\n\n\n/**\n * Adds a `getInstance` static method that always returns the same\n * instance object.\n * @param {!Function} ctor The constructor for the class to add the static\n * method to.\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\n * but we don't have a better type to use here.\n */\ngoog.addSingletonGetter = function(ctor) {\n // instance_ is immediately set to prevent issues with sealed constructors\n // such as are encountered when a constructor is returned as the export object\n // of a goog.module in unoptimized code.\n // Delcare type to avoid conformance violations that ctor.instance_ is unknown\n /** @type {undefined|!Object} @suppress {underscore} */\n ctor.instance_ = undefined;\n ctor.getInstance = function() {\n if (ctor.instance_) {\n return ctor.instance_;\n }\n if (goog.DEBUG) {\n // NOTE: JSCompiler can't optimize away Array#push.\n goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\n }\n // Cast to avoid conformance violations that ctor.instance_ is unknown\n return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\n };\n};\n\n\n/**\n * All singleton classes that have been instantiated, for testing. Don't read\n * it directly, use the `goog.testing.singleton` module. The compiler\n * removes this variable if unused.\n * @type {!Array<!Function>}\n * @private\n */\ngoog.instantiatedSingletons_ = [];\n\n\n/**\n * @define {boolean} Whether to load goog.modules using `eval` when using\n * the debug loader. This provides a better debugging experience as the\n * source is unmodified and can be edited using Chrome Workspaces or similar.\n * However in some environments the use of `eval` is banned\n * so we provide an alternative.\n */\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\n\n\n/**\n * @define {boolean} Whether the exports of goog.modules should be sealed when\n * possible.\n */\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\n\n\n/**\n * The registry of initialized modules:\n * The module identifier or path to module exports map.\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\n */\ngoog.loadedModules_ = {};\n\n\n/**\n * True if the debug loader enabled and used.\n * @const {boolean}\n */\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\n\n\n/**\n * @define {string} How to decide whether to transpile. Valid values\n * are 'always', 'never', and 'detect'. The default ('detect') is to\n * use feature detection to determine which language levels need\n * transpilation.\n */\n// NOTE(sdh): we could expand this to accept a language level to bypass\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\n// would leave ES3 and ES5 files alone.\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\n\n/**\n * @define {boolean} If true assume that ES modules have already been\n * transpiled by the jscompiler (in the same way that transpile.js would\n * transpile them - to jscomp modules). Useful only for servers that wish to use\n * the debug loader and transpile server side. Thus this is only respected if\n * goog.TRANSPILE is \"never\".\n */\ngoog.ASSUME_ES_MODULES_TRANSPILED =\n goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\n\n\n/**\n * @define {string} 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', 'goog');\n\n\n/**\n * @package {?boolean}\n * Visible for testing.\n */\ngoog.hasBadLetScoping = null;\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 origExports = {};\n var exports = origExports;\n if (typeof moduleDef === 'function') {\n exports = moduleDef.call(undefined, exports);\n } else if (typeof moduleDef === 'string') {\n exports = goog.loadModuleFromSource_.call(undefined, exports, moduleDef);\n } else {\n throw new Error('Invalid module definition');\n }\n\n var moduleName = goog.moduleLoaderState_.moduleName;\n if (typeof moduleName === 'string' && moduleName) {\n // Don't seal legacy namespaces as they may be used as a parent of\n // another namespace\n if (goog.moduleLoaderState_.declareLegacyNamespace) {\n // Whether exports was overwritten via default export assignment.\n // This is important for legacy namespaces as it dictates whether\n // previously a previously loaded implicit namespace should be clobbered\n // or not.\n var isDefaultExport = origExports !== exports;\n goog.constructNamespace_(moduleName, exports, isDefaultExport);\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_ =\n /** @type {function(!Object, string):?} */ (function(exports) {\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 eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(arguments[1]));\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// 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\n if (s != 'object') {\n return s;\n }\n\n if (!value) {\n return 'null';\n }\n\n if (Array.isArray(value)) {\n return 'array';\n }\n return s;\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 an object. This includes arrays and\n * functions.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an object.\n */\ngoog.isObject = function(val) {\n var type = typeof val;\n return type == 'object' && val != null || type == 'function';\n // return Object(val) === val also works, but is slower, especially if val is\n // not an object.\n};\n\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. The unique ID is\n * guaranteed to be unique across the current session amongst objects that are\n * passed into `getUid`. There is no guarantee that the ID is unique or\n * consistent across sessions. It is unsafe to generate unique ID for function\n * prototypes.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {number} The unique ID for the object.\n */\ngoog.getUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n return Object.prototype.hasOwnProperty.call(obj, goog.UID_PROPERTY_) &&\n obj[goog.UID_PROPERTY_] ||\n (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\n};\n\n\n/**\n * Whether the given object is already assigned a unique ID.\n *\n * This does not modify the object.\n *\n * @param {!Object} obj The object to check.\n * @return {boolean} Whether there is an assigned unique id for the object.\n */\ngoog.hasUid = function(obj) {\n return !!obj[goog.UID_PROPERTY_];\n};\n\n\n/**\n * Removes the unique ID from an object. This is useful if the object was\n * previously mutated using `goog.getUid` in which case the mutation is\n * undone.\n * @param {Object} obj The object to remove the unique ID field from.\n */\ngoog.removeUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n\n // In IE, DOM nodes are not instances of Object and throw an exception if we\n // try to delete. Instead we try to use removeAttribute.\n if (obj !== null && 'removeAttribute' in obj) {\n obj.removeAttribute(goog.UID_PROPERTY_);\n }\n\n try {\n delete obj[goog.UID_PROPERTY_];\n } catch (ex) {\n }\n};\n\n\n/**\n * Name for unique ID property. Initialized in a way to help avoid collisions\n * with other closure JavaScript on the same page.\n * @type {string}\n * @private\n */\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * Counter for UID.\n * @type {number}\n * @private\n */\ngoog.uidCounter_ = 0;\n\n\n/**\n * 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 if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\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 * @deprecated use `=> {}` or Function.prototype.bind instead.\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 * @return {number} An integer value representing the number of milliseconds\n * between midnight, January 1, 1970 and the current time.\n * @deprecated Use Date.now\n */\ngoog.now = function() {\n return Date.now();\n};\n\n\n/**\n * Evals JavaScript in the global scope.\n *\n * Throws an exception if neither execScript or eval is defined.\n * @param {string|!TrustedScript} script JavaScript string.\n */\ngoog.globalEval = function(script) {\n (0, eval)(script);\n};\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 * Options bag type for `goog.getMsg()` third argument.\n *\n * It is important to note that these options need to be known at compile time,\n * so they must always be provided to `goog.getMsg()` as an actual object\n * literal in the function call. Otherwise, closure-compiler will report an\n * error.\n * @record\n */\ngoog.GetMsgOptions = function() {};\n\n/**\n * If `true`, escape '<' in the message string to '&lt;'.\n *\n * Used by Closure Templates where the generated code size and performance is\n * critical which is why {@link goog.html.SafeHtmlFormatter} is not used.\n * The value must be literal `true` or `false`.\n * @type {boolean|undefined}\n */\ngoog.GetMsgOptions.prototype.html;\n\n/**\n * If `true`, unescape common html entities: &gt;, &lt;, &apos;, &quot; and\n * &amp;.\n *\n * Used for messages not in HTML context, such as with the `textContent`\n * property.\n * The value must be literal `true` or `false`.\n * @type {boolean|undefined}\n */\ngoog.GetMsgOptions.prototype.unescapeHtmlEntities;\n\n/**\n * Associates placeholder names with strings showing how their values are\n * obtained.\n *\n * This field is intended for use in automatically generated JS code.\n * Human-written code should use meaningful placeholder names instead.\n *\n * closure-compiler uses this as the contents of the `<ph>` tag in the\n * XMB file it generates or defaults to `-` for historical reasons.\n *\n * Must be an object literal.\n * Ignored at runtime.\n * Keys are placeholder names.\n * Values are string literals indicating how the value is obtained.\n * Typically this is a snippet of source code.\n * @type {!Object<string, string>|undefined}\n */\ngoog.GetMsgOptions.prototype.original_code;\n\n/**\n * Associates placeholder names with example values.\n *\n * closure-compiler uses this as the contents of the `<ex>` tag in the\n * XMB file it generates or defaults to `-` for historical reasons.\n *\n * Must be an object literal.\n * Ignored at runtime.\n * Keys are placeholder names.\n * Values are string literals containing example placeholder values.\n * (e.g. \"George McFly\" for a name placeholder)\n * @type {!Object<string, string>|undefined}\n */\ngoog.GetMsgOptions.prototype.example;\n\n/**\n * Gets a localized message.\n *\n * This function is a compiler primitive. If you give the compiler a localized\n * message bundle, it will replace the string at compile-time with a localized\n * version, and expand goog.getMsg call to a concatenated string.\n *\n * Messages must be initialized in the form:\n * <code>\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\n * </code>\n *\n * This function produces a string which should be treated as plain text. Use\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\n * produce SafeHtml.\n *\n * @param {string} str Translatable string, places holders in the form {$foo}.\n * @param {!Object<string, string>=} opt_values Maps place holder name to value.\n * @param {!goog.GetMsgOptions=} opt_options see `goog.GetMsgOptions`\n * @return {string} message with placeholders filled.\n */\ngoog.getMsg = function(str, opt_values, opt_options) {\n if (opt_options && opt_options.html) {\n // Note that '&' is not replaced because the translation can contain HTML\n // entities.\n str = str.replace(/</g, '&lt;');\n }\n if (opt_options && opt_options.unescapeHtmlEntities) {\n // Note that \"&amp;\" must be the last to avoid \"creating\" new entities.\n str = str.replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&apos;/g, '\\'')\n .replace(/&quot;/g, '\"')\n .replace(/&amp;/g, '&');\n }\n if (opt_values) {\n str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\n return (opt_values != null && key in opt_values) ? opt_values[key] :\n match;\n });\n }\n return str;\n};\n\n\n/**\n * Gets a localized message. If the message does not have a translation, gives a\n * fallback message.\n *\n * This is useful when introducing a new message that has not yet been\n * translated into all languages.\n *\n * This function is a compiler primitive. Must be used in the form:\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\n * where MSG_A and MSG_B were initialized with goog.getMsg.\n *\n * @param {string} a The preferred message.\n * @param {string} b The fallback message.\n * @return {string} The best translated message.\n */\ngoog.getMsgWithFallback = function(a, b) {\n return a;\n};\n\n\n/**\n * Exposes an unobfuscated global namespace path for the given object.\n * Note that fields of the exported object *will* be obfuscated, unless they are\n * exported in turn via this function or goog.exportProperty.\n *\n * Also handy for making public items that are defined in anonymous closures.\n *\n * ex. goog.exportSymbol('public.path.Foo', Foo);\n *\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\n * public.path.Foo.staticFunction();\n *\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\n * Foo.prototype.myMethod);\n * new public.path.Foo().myMethod();\n *\n * @param {string} publicPath Unobfuscated name to export.\n * @param {*} object Object the name should point to.\n * @param {?Object=} objectToExportTo The object to add the path to; default\n * is goog.global.\n */\ngoog.exportSymbol = function(publicPath, object, objectToExportTo) {\n goog.exportPath_(\n publicPath, object, /* overwriteImplicit= */ true, 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 * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.inherits = function(childCtor, parentCtor) {\n /** @constructor */\n function tempCtor() {}\n tempCtor.prototype = parentCtor.prototype;\n childCtor.superClass_ = parentCtor.prototype;\n childCtor.prototype = new tempCtor();\n /** @override */\n childCtor.prototype.constructor = childCtor;\n\n /**\n * Calls superclass constructor/method.\n *\n * This function is only available if you use goog.inherits to\n * express inheritance relationships between classes.\n *\n * NOTE: This is a replacement for goog.base and for superClass_\n * property defined in childCtor.\n *\n * @param {!Object} me Should always be \"this\".\n * @param {string} methodName The method name to call. Calling\n * superclass constructor can be done with the special string\n * 'constructor'.\n * @param {...*} var_args The arguments to pass to superclass\n * method/constructor.\n * @return {*} The return value of the superclass method/constructor.\n */\n childCtor.base = function(me, methodName, var_args) {\n // Copying using loop to avoid deop due to passing arguments object to\n // function. This is faster in many JS engines as of late 2014.\n var args = new Array(arguments.length - 2);\n for (var i = 2; i < arguments.length; i++) {\n args[i - 2] = arguments[i];\n }\n return parentCtor.prototype[methodName].apply(me, args);\n };\n};\n\n\n/**\n * Allow for aliasing within scope functions. This function exists for\n * uncompiled code - in compiled code the calls will be inlined and the aliases\n * applied. In uncompiled code the function is simply run since the aliases as\n * written are valid JavaScript.\n *\n *\n * @param {function()} fn Function to call. This function can contain aliases\n * to namespaces (e.g. \"var dom = goog.dom\") or classes\n * (e.g. \"var Timer = goog.Timer\").\n * @deprecated Use goog.module instead.\n */\ngoog.scope = function(fn) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.scope is not supported within a module.');\n }\n fn.call(goog.global);\n};\n\n\n/*\n * To support uncompiled, strict mode bundles that use eval to divide source\n * like so:\n * eval('someSource;//# sourceUrl sourcefile.js');\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\n * be defined externally.\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\n * extern generation when that compiler option is enabled.\n */\nif (!COMPILED) {\n goog.global['COMPILED'] = COMPILED;\n}\n\n\n//==============================================================================\n// goog.defineClass implementation\n//==============================================================================\n\n\n/**\n * Creates a restricted form of a Closure \"class\":\n * - from the compiler's perspective, the instance returned from the\n * constructor is sealed (no new properties may be added). This enables\n * better checks.\n * - the compiler will rewrite this definition to a form that is optimal\n * for type checking and optimization (initially this will be a more\n * traditional form).\n *\n * @param {Function} superClass The superclass, Object or null.\n * @param {goog.defineClass.ClassDescriptor} def\n * An object literal describing\n * the class. It may have the following properties:\n * \"constructor\": the constructor function\n * \"statics\": an object literal containing methods to add to the constructor\n * as \"static\" methods or a function that will receive the constructor\n * function as its only parameter to which static properties can\n * be added.\n * all other properties are added to the prototype.\n * @return {!Function} The class constructor.\n * @deprecated Use ECMAScript 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 // NOTE: The sealing behavior has been removed\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 return instance;\n };\n\n return wrappedCtr;\n};\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 * 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 var policyFactory = goog.global.trustedTypes;\n if (!policyFactory || !policyFactory.createPolicy) {\n return policy;\n }\n // trustedTypes.createPolicy throws if called with a name that is already\n // registered, even in report-only mode. Until the API changes, catch the\n // error not to break the applications functionally. In such case, the code\n // will fall back to using regular Safe Types.\n // TODO(koto): Remove catching once createPolicy API stops throwing.\n try {\n policy = policyFactory.createPolicy(name, {\n createHTML: goog.identity_,\n createScript: goog.identity_,\n createScriptURL: goog.identity_\n });\n } catch (e) {\n goog.logToConsole_(e.message);\n }\n return policy;\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 /**\n * Tries to detect whether the current browser is Edge, based on the user\n * agent. This matches only pre-Chromium Edge.\n * @see https://docs.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-string\n * @return {boolean} True if the current browser is Edge.\n * @private\n */\n goog.isEdge_ = function() {\n var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\n goog.global.navigator.userAgent :\n '';\n var edgeRe = /Edge\\/(\\d+)(\\.\\d)*/i;\n return !!userAgent.match(edgeRe);\n };\n\n\n /**\n * Tries to detect whether is in the context of an HTML document.\n * @return {boolean} True if it looks like HTML document.\n * @private\n */\n goog.inHtmlDocument_ = function() {\n /** @type {!Document} */\n var doc = goog.global.document;\n return doc != null && 'write' in doc; // XULDocument misses write.\n };\n\n\n /**\n * We'd like to check for if the document readyState is 'loading'; however\n * there are bugs on IE 10 and below where the readyState being anything other\n * than 'complete' is not reliable.\n * @return {boolean}\n * @private\n */\n goog.isDocumentLoading_ = function() {\n // attachEvent is available on IE 6 thru 10 only, and thus can be used to\n // detect those browsers.\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n return doc.attachEvent ? doc.readyState != 'complete' :\n doc.readyState == 'loading';\n };\n\n\n /**\n * Tries to detect the base path of base.js script that bootstraps Closure.\n * @private\n */\n goog.findBasePath_ = function() {\n if (goog.global.CLOSURE_BASE_PATH != undefined &&\n // Anti DOM-clobbering runtime check (b/37736576).\n typeof goog.global.CLOSURE_BASE_PATH === 'string') {\n goog.basePath = goog.global.CLOSURE_BASE_PATH;\n return;\n } else if (!goog.inHtmlDocument_()) {\n return;\n }\n /** @type {!Document} */\n var doc = goog.global.document;\n // If we have a currentScript available, use it exclusively.\n var currentScript = doc.currentScript;\n if (currentScript) {\n var scripts = [currentScript];\n } else {\n var scripts = doc.getElementsByTagName('SCRIPT');\n }\n // Search backwards since the current script is in almost all cases the one\n // that has base.js.\n for (var i = scripts.length - 1; i >= 0; --i) {\n var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\n var src = script.src;\n var qmark = src.lastIndexOf('?');\n var l = qmark == -1 ? src.length : qmark;\n if (src.slice(l - 7, l) == 'base.js') {\n goog.basePath = src.slice(0, l - 7);\n return;\n }\n }\n };\n\n goog.findBasePath_();\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();\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 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 goog.logToConsole_(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 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 var nonce = goog.getScriptNonce_();\n if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\n goog.isDocumentLoading_()) {\n var key;\n var callback = function(script) {\n if (script.readyState && script.readyState != 'complete') {\n script.onload = callback;\n return;\n }\n goog.Dependency.unregisterCallback_(key);\n controller.loaded();\n };\n key = goog.Dependency.registerCallback_(callback);\n\n var defer = goog.Dependency.defer_ ? ' defer' : '';\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script src=\"' + this.path + '\"' + nonceAttr + defer +\n ' id=\"script-' + key + '\"><\\/script>';\n\n script += '<script' + nonceAttr + '>';\n\n if (goog.Dependency.defer_) {\n script += 'document.getElementById(\\'script-' + key +\n '\\').onload = function() {\\n' +\n ' goog.Dependency.callback_(\\'' + key + '\\', this);\\n' +\n '};\\n';\n } else {\n script += 'goog.Dependency.callback_(\\'' + key +\n '\\', document.getElementById(\\'script-' + key + '\\'));';\n }\n\n script += '<\\/script>';\n\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\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 if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n scriptEl.onload = function() {\n scriptEl.onload = null;\n controller.loaded();\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 /**\n * @override\n * @param {!goog.LoadController} controller\n */\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 var nonceAttr = '';\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n nonceAttr = ' nonce=\"' + nonce + '\"';\n }\n\n if (contents) {\n var script = '<script type=\"module\" crossorigin' + nonceAttr + '>' +\n 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 nonceAttr + '></' +\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.nonce = nonce;\n }\n\n if (contents) {\n scriptEl.text = 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 /**\n * @override\n * @param {!goog.LoadController} controller\n */\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(goog.CLOSURE_EVAL_PREFILTER_.createScript(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 nonce = goog.getScriptNonce_();\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script' + nonceAttr + '>' +\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 // 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 (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 isInternetExplorerOrEdge = goog.inHtmlDocument_() &&\n ('ActiveXObject' in goog.global || goog.isEdge_());\n\n // Don't delay in any version of IE or pre-Chromium Edge. There's a bug\n // around this that will cause out of order script execution. This means\n // that on older IE ES6 modules will load too early (while the document is\n // still loading + the dom is not available). The other option is to load\n // too late (when the document is complete and the onload even will never\n // fire). This seems to be the lesser of two evils as scripts already act\n // like the former.\n if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\n !isInternetExplorerOrEdge) {\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 (typeof oldCallback === 'function') {\n oldCallback.apply(undefined, arguments);\n }\n };\n } else {\n // Always eval on old IE.\n if (!goog.inHtmlDocument_() || !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 * 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 /**\n * @override\n * @param {string} contents\n * @return {string}\n */\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 * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.GoogModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.GoogModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.GoogModuleDependency.prototype.transform = function(contents) {\n if (!goog.LOAD_MODULE_USING_EVAL || goog.global.JSON === undefined) {\n return '' +\n 'goog.loadModule(function(exports) {' +\n '\"use strict\";' + contents +\n '\\n' + // terminate any trailing single line comment.\n ';return exports' +\n '});' +\n '\\n//# sourceURL=' + this.path + '\\n';\n } else {\n return '' +\n 'goog.loadModule(' +\n goog.global.JSON.stringify(\n contents + '\\n//# sourceURL=' + this.path + '\\n') +\n ');';\n }\n };\n\n\n /**\n * @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 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 * @struct @constructor\n */\n goog.DependencyFactory = function() {};\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 * @return {!goog.Dependency}\n */\n goog.DependencyFactory.prototype.createDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n\n if (loadFlags['module'] == goog.ModuleType.GOOG) {\n return new goog.GoogModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n } else {\n if (loadFlags['module'] == goog.ModuleType.ES6) {\n if (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 /**\n * Trusted Types policy for the debug loader.\n * @private @const {?TrustedTypePolicy}\n */\n goog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\n goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\n null;\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\nif (!COMPILED) {\n var isChrome87 = false;\n // Cannot run check for Chrome <87 bug in case of strict CSP environments.\n // TODO(user): Remove once Chrome <87 bug is no longer a problem.\n try {\n isChrome87 = eval(goog.global.trustedTypes.emptyScript) !==\n goog.global.trustedTypes.emptyScript;\n } catch (err) {\n }\n\n /**\n * Trusted Types for running dev servers.\n *\n * @private @const\n */\n goog.CLOSURE_EVAL_PREFILTER_ =\n // Detect Chrome <87 bug with TT and eval.\n goog.global.trustedTypes && isChrome87 &&\n goog.createTrustedTypesPolicy('goog#base#devonly#eval') ||\n {createScript: goog.identity_};\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implements the disposable interface.\n */\n\ngoog.provide('goog.Disposable');\n\ngoog.require('goog.disposable.IDisposable');\ngoog.require('goog.dispose');\n/**\n * TODO(user): Remove this require.\n * @suppress {extraRequire}\n */\ngoog.require('goog.disposeAll');\n\n/**\n * Class that provides the basic implementation for disposable objects. If your\n * class holds references or resources that can't be collected by standard GC,\n * it should extend this class or implement the disposable interface (defined\n * in goog.disposable.IDisposable). See description of\n * goog.disposable.IDisposable for examples of cleanup.\n * @constructor\n * @implements {goog.disposable.IDisposable}\n */\ngoog.Disposable = function() {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n return this.disposed_;\n};\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @deprecated Use {@link #isDisposed} instead.\n */\ngoog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;\n\n\n/**\n * Disposes of the object. If the object hasn't already been disposed of, calls\n * {@link #disposeInternal}. Classes that extend `goog.Disposable` should\n * override {@link #disposeInternal} in order to cleanup references, resources\n * and other disposable objects. Reentrant.\n *\n * @return {void} Nothing.\n * @override\n */\ngoog.Disposable.prototype.dispose = function() {\n 'use strict';\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 'use strict';\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 'use strict';\n if (this.disposed_) {\n opt_scope !== undefined ? callback.call(opt_scope) : callback();\n return;\n }\n if (!this.onDisposeCallbacks_) {\n this.onDisposeCallbacks_ = [];\n }\n\n this.onDisposeCallbacks_.push(\n opt_scope !== undefined ? goog.bind(callback, opt_scope) : callback);\n};\n\n\n/**\n * Performs appropriate cleanup. See description of goog.disposable.IDisposable\n * for examples. Classes that extend `goog.Disposable` should override this\n * method. Not reentrant. To avoid calling it twice, it must only be called from\n * the subclass' `disposeInternal` method. Everywhere else the public `dispose`\n * method must be used. For example:\n *\n * <pre>\n * mypackage.MyClass = function() {\n * mypackage.MyClass.base(this, 'constructor');\n * // Constructor logic specific to MyClass.\n * ...\n * };\n * goog.inherits(mypackage.MyClass, goog.Disposable);\n *\n * mypackage.MyClass.prototype.disposeInternal = function() {\n * // Dispose logic specific to MyClass.\n * ...\n * // Call superclass's disposeInternal at the end of the subclass's, like\n * // in C++, to avoid hard-to-catch issues.\n * mypackage.MyClass.base(this, 'disposeInternal');\n * };\n * </pre>\n *\n * @protected\n */\ngoog.Disposable.prototype.disposeInternal = function() {\n 'use strict';\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 'use strict';\n if (obj && typeof obj.isDisposed == 'function') {\n return obj.isDisposed();\n }\n return false;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating arrays.\n */\n\n\ngoog.module('goog.array');\ngoog.module.declareLegacyNamespace();\n\nconst asserts = goog.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 */\nconst ASSUME_NATIVE_FUNCTIONS = goog.define(\n 'goog.array.ASSUME_NATIVE_FUNCTIONS', goog.FEATURESET_YEAR > 2012);\nexports.ASSUME_NATIVE_FUNCTIONS = ASSUME_NATIVE_FUNCTIONS;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.last}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nfunction peek(array) {\n return array[array.length - 1];\n}\nexports.peek = peek;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.peek}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nexports.last = 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 */\nconst indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n const fromIndex = opt_fromIndex == null ?\n 0 :\n (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :\n opt_fromIndex);\n\n if (typeof arr === 'string') {\n // Array.prototype.indexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.indexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i < arr.length; i++) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.indexOf = indexOf;\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 */\nconst lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?\n function(arr, obj, opt_fromIndex) {\n 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 const 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 let fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n\n if (fromIndex < 0) {\n fromIndex = Math.max(0, arr.length + fromIndex);\n }\n\n if (typeof arr === 'string') {\n // Array.prototype.lastIndexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.lastIndexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i >= 0; i--) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.lastIndexOf = lastIndexOf;\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 */\nconst forEach = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n Array.prototype.forEach.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n };\nexports.forEach = forEach;\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 */\nfunction forEachRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; --i) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n}\nexports.forEachRight = forEachRight;\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 */\nconst filter = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.filter.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = [];\n let resLength = 0;\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n const 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 };\nexports.filter = filter;\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 */\nconst map = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.map.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = new Array(l);\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let 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 };\nexports.map = map;\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 * Note that this implementation differs from the native Array.prototype.reduce\n * in that the initial value is assumed to be defined (the MDN docs linked above\n * recommend not omitting this parameter, although it is technically optional).\n *\n * For example:\n * var a = [1, 2, 3, 4];\n * 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 */\nconst reduce = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?\n function(arr, f, val, opt_obj) {\n 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 let rval = val;\n forEach(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduce = reduce;\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 * 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 */\nconst reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n 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 let rval = val;\n forEachRight(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduceRight = reduceRight;\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 */\nconst some = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.some.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let 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 };\nexports.some = some;\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 */\nconst every = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.every.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let 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 };\nexports.every = every;\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 */\nfunction count(arr, f, opt_obj) {\n let count = 0;\n 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}\nexports.count = count;\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 */\nfunction find(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.find = find;\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 */\nfunction findIndex(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let 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}\nexports.findIndex = findIndex;\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 */\nfunction findRight(arr, f, opt_obj) {\n const i = findIndexRight(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.findRight = findRight;\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 */\nfunction findIndexRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let 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}\nexports.findIndexRight = findIndexRight;\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 */\nfunction contains(arr, obj) {\n return indexOf(arr, obj) >= 0;\n}\nexports.contains = contains;\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 */\nfunction isEmpty(arr) {\n return arr.length == 0;\n}\nexports.isEmpty = isEmpty;\n\n\n/**\n * Clears the array.\n * @param {IArrayLike<?>} arr Array or array like object to clear.\n */\nfunction clear(arr) {\n // For non real arrays we don't have the magic length so we delete the\n // indices.\n if (!Array.isArray(arr)) {\n for (let i = arr.length - 1; i >= 0; i--) {\n delete arr[i];\n }\n }\n arr.length = 0;\n}\nexports.clear = clear;\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 */\nfunction insert(arr, obj) {\n if (!contains(arr, obj)) {\n arr.push(obj);\n }\n}\nexports.insert = insert;\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 */\nfunction insertAt(arr, obj, opt_i) {\n splice(arr, opt_i, 0, obj);\n}\nexports.insertAt = insertAt;\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 */\nfunction insertArrayAt(arr, elementsToAdd, opt_i) {\n goog.partial(splice, arr, opt_i, 0).apply(null, elementsToAdd);\n}\nexports.insertArrayAt = insertArrayAt;\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 */\nfunction insertBefore(arr, obj, opt_obj2) {\n let i;\n if (arguments.length == 2 || (i = indexOf(arr, opt_obj2)) < 0) {\n arr.push(obj);\n } else {\n insertAt(arr, obj, i);\n }\n}\nexports.insertBefore = insertBefore;\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 */\nfunction remove(arr, obj) {\n const i = indexOf(arr, obj);\n let rv;\n if ((rv = i >= 0)) {\n removeAt(arr, i);\n }\n return rv;\n}\nexports.remove = remove;\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 */\nfunction removeLast(arr, obj) {\n const i = lastIndexOf(arr, obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeLast = removeLast;\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 */\nfunction removeAt(arr, i) {\n 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}\nexports.removeAt = removeAt;\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 */\nfunction removeIf(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeIf = removeIf;\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 */\nfunction removeAllIf(arr, f, opt_obj) {\n let removedCount = 0;\n forEachRight(arr, function(val, index) {\n if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {\n if (removeAt(arr, index)) {\n removedCount++;\n }\n }\n });\n return removedCount;\n}\nexports.removeAllIf = removeAllIf;\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 * concat([1, 2], [3, 4]) -> [1, 2, 3, 4]\n * concat(0, [1, 2]) -> [0, 1, 2]\n * concat([1, 2], null) -> [1, 2, null]\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 */\nfunction concat(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.concat = concat;\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 */\nfunction join(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.join = join;\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 */\nfunction toArray(object) {\n const 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 const rv = new Array(length);\n for (let i = 0; i < length; i++) {\n rv[i] = object[i];\n }\n return rv;\n }\n return [];\n}\nexports.toArray = toArray;\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 */\nconst clone = toArray;\nexports.clone = clone;\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 * extend(a, [0, 1]);\n * a; // [0, 1]\n * 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 */\nfunction extend(arr1, var_args) {\n for (let i = 1; i < arguments.length; i++) {\n const arr2 = arguments[i];\n if (goog.isArrayLike(arr2)) {\n const len1 = arr1.length || 0;\n const len2 = arr2.length || 0;\n arr1.length = len1 + len2;\n for (let j = 0; j < len2; j++) {\n arr1[len1 + j] = arr2[j];\n }\n } else {\n arr1.push(arr2);\n }\n }\n}\nexports.extend = extend;\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 */\nfunction splice(arr, index, howMany, var_args) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.splice.apply(arr, slice(arguments, 1));\n}\nexports.splice = splice;\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 */\nfunction slice(arr, start, opt_end) {\n 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}\nexports.slice = slice;\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 */\nfunction removeDuplicates(arr, opt_rv, opt_hashFn) {\n const returnArray = opt_rv || arr;\n const 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 const hashFn = opt_hashFn || defaultHashFn;\n\n let cursorInsert = 0;\n let cursorRead = 0;\n const seen = {};\n\n while (cursorRead < arr.length) {\n const current = arr[cursorRead++];\n const 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}\nexports.removeDuplicates = removeDuplicates;\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>defaultCompare</code>, which compares the elements\n * using the built in < and > operators. This will produce the expected\n * behavior for homogeneous arrays of String(s) and Number(s). The array\n * specified <b>must</b> be sorted in ascending order (as defined by the\n * comparison function). If the array is not sorted, results are undefined.\n * If the array contains multiple instances of the specified target value, the\n * left-most instance will be found.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {TARGET} target The sought value.\n * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, the target value and an element from your array, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @template TARGET, VALUE\n */\nfunction binarySearch(arr, target, opt_compareFn) {\n return binarySearch_(\n arr, opt_compareFn || defaultCompare, false /* isEvaluator */, target);\n}\nexports.binarySearch = binarySearch;\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 * map(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 */\nfunction binarySelect(arr, evaluator, opt_obj) {\n return binarySearch_(\n arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,\n opt_obj);\n}\nexports.binarySelect = binarySelect;\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 */\nfunction binarySearch_(arr, compareFn, isEvaluator, opt_target, opt_selfObj) {\n let left = 0; // inclusive\n let right = arr.length; // exclusive\n let found;\n while (left < right) {\n const middle = left + ((right - left) >>> 1);\n let compareResult;\n if (isEvaluator) {\n compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);\n } else {\n // NOTE(dimvar): To avoid this cast, we'd have to use function overloading\n // for the type of binarySearch_, which the type system can't express yet.\n compareResult = /** @type {function(?, ?): number} */ (compareFn)(\n opt_target, arr[middle]);\n }\n if (compareResult > 0) {\n left = middle + 1;\n } else {\n right = middle;\n // We are looking for the lowest index so we can't return immediately.\n found = !compareResult;\n }\n }\n // left is the index if found, or the insertion point otherwise.\n // Avoiding bitwise not operator, as that causes a loss in precision for array\n // indexes outside the bounds of a 32-bit signed integer. Array indexes have\n // a maximum value of 2^32-2 https://tc39.es/ecma262/#array-index\n return found ? left : -left - 1;\n}\n\n\n/**\n * Sorts the specified array into ascending order. If no opt_compareFn is\n * specified, elements are compared using\n * <code>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 `Array.prototype.sort`\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 */\nfunction sort(arr, opt_compareFn) {\n // TODO(arv): Update type annotation since null is not accepted.\n arr.sort(opt_compareFn || defaultCompare);\n}\nexports.sort = sort;\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>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 `Array.prototype.sort`, 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 */\nfunction stableSort(arr, opt_compareFn) {\n const compArr = new Array(arr.length);\n for (let i = 0; i < arr.length; i++) {\n compArr[i] = {index: i, value: arr[i]};\n }\n const valueCompareFn = opt_compareFn || defaultCompare;\n function stableCompareFn(obj1, obj2) {\n return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;\n }\n sort(compArr, stableCompareFn);\n for (let i = 0; i < arr.length; i++) {\n arr[i] = compArr[i].value;\n }\n}\nexports.stableSort = stableSort;\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>defaultCompare</code>.\n *\n * Runtime: O(S(f(n)), where S is runtime of <code>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 */\nfunction sortByKey(arr, keyFn, opt_compareFn) {\n const keyCompareFn = opt_compareFn || defaultCompare;\n sort(arr, function(a, b) {\n return keyCompareFn(keyFn(a), keyFn(b));\n });\n}\nexports.sortByKey = sortByKey;\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>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 */\nfunction sortObjectsByKey(arr, key, opt_compareFn) {\n sortByKey(arr, function(obj) {\n return obj[key];\n }, opt_compareFn);\n}\nexports.sortObjectsByKey = sortObjectsByKey;\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 */\nfunction isSorted(arr, opt_compareFn, opt_strict) {\n const compare = opt_compareFn || defaultCompare;\n for (let i = 1; i < arr.length; i++) {\n const compareResult = compare(arr[i - 1], arr[i]);\n if (compareResult > 0 || compareResult == 0 && opt_strict) {\n return false;\n }\n }\n return true;\n}\nexports.isSorted = isSorted;\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<A>} arr1 The first array to compare.\n * @param {IArrayLike<B>} arr2 The second array to compare.\n * @param {?function(A,B):boolean=} 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 * @template A\n * @template B\n */\nfunction equals(arr1, arr2, opt_equalsFn) {\n if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||\n arr1.length != arr2.length) {\n return false;\n }\n const l = arr1.length;\n const equalsFn = opt_equalsFn || defaultCompareEquality;\n for (let i = 0; i < l; i++) {\n if (!equalsFn(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nexports.equals = equals;\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 */\nfunction compare3(arr1, arr2, opt_compareFn) {\n const compare = opt_compareFn || defaultCompare;\n const l = Math.min(arr1.length, arr2.length);\n for (let i = 0; i < l; i++) {\n const result = compare(arr1[i], arr2[i]);\n if (result != 0) {\n return result;\n }\n }\n return defaultCompare(arr1.length, arr2.length);\n}\nexports.compare3 = compare3;\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 */\nfunction defaultCompare(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n}\nexports.defaultCompare = defaultCompare;\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 */\nfunction inverseDefaultCompare(a, b) {\n return -defaultCompare(a, b);\n}\nexports.inverseDefaultCompare = inverseDefaultCompare;\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 */\nfunction defaultCompareEquality(a, b) {\n return a === b;\n}\nexports.defaultCompareEquality = defaultCompareEquality;\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 */\nfunction binaryInsert(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n if (index < 0) {\n insertAt(array, value, -(index + 1));\n return true;\n }\n return false;\n}\nexports.binaryInsert = binaryInsert;\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 */\nfunction binaryRemove(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n return (index >= 0) ? removeAt(array, index) : false;\n}\nexports.binaryRemove = binaryRemove;\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 */\nfunction bucket(array, sorter, opt_obj) {\n const buckets = {};\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n const bucket = buckets[key] || (buckets[key] = []);\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucket = bucket;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {!IArrayLike<V>} array The array.\n * @param {function(V, number, !IArrayLike<V>):(K|undefined)} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index,\n * and the array) and must return a value to use as a key, or undefined, if\n * that object should not be placed in a bucket.\n * @return {!Map<K, !Array<V>>} A map, 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 K,V\n */\nfunction bucketToMap(array, sorter) {\n const /** !Map<K, !Array<V>> */ buckets = new Map();\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter(value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = [];\n buckets.set(key, bucket);\n }\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucketToMap = bucketToMap;\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 */\nfunction toObject(arr, keyFunc, opt_obj) {\n const ret = {};\n forEach(arr, function(element, index) {\n ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =\n element;\n });\n return ret;\n}\nexports.toObject = toObject;\n\n\n/**\n * Creates a new ES6 Map built from the provided array and the key-generation\n * function.\n * @param {!IArrayLike<V>} arr Array or array like object over which to iterate\n * whose elements will be the values in the new object.\n * @param {?function(V, number, ?) : K} keyFunc The function to call for every\n * element. This function takes 3 arguments (the element, the index, and the\n * array) and should return a value that will be used as the key for the\n * element in the new object. If the function returns the same key for more\n * than one element, the value for that key is implementation-defined.\n * @return {!Map<K, V>} The new map.\n * @template K,V\n */\nfunction toMap(arr, keyFunc) {\n const /** !Map<K, V> */ map = new Map();\n\n for (let i = 0; i < arr.length; i++) {\n const element = arr[i];\n map.set(keyFunc(element, i, arr), element);\n }\n\n return map;\n}\nexports.toMap = toMap;\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 */\nfunction range(startOrEnd, opt_end, opt_step) {\n const array = [];\n let start = 0;\n let end = startOrEnd;\n const 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 (let i = start; i < end; i += step) {\n array.push(i);\n }\n } else {\n for (let i = start; i > end; i += step) {\n array.push(i);\n }\n }\n return array;\n}\nexports.range = range;\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 */\nfunction repeat(value, n) {\n const array = [];\n for (let i = 0; i < n; i++) {\n array[i] = value;\n }\n return array;\n}\nexports.repeat = repeat;\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 */\nfunction flatten(var_args) {\n const CHUNK_SIZE = 8192;\n\n const result = [];\n for (let i = 0; i < arguments.length; i++) {\n const element = arguments[i];\n if (Array.isArray(element)) {\n for (let c = 0; c < element.length; c += CHUNK_SIZE) {\n const chunk = slice(element, c, c + CHUNK_SIZE);\n const recurseResult = flatten.apply(null, chunk);\n for (let 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}\nexports.flatten = flatten;\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 */\nfunction rotate(array, n) {\n 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}\nexports.rotate = rotate;\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 * `arr.length - 1`.\n * @param {number} toIndex Target index between 0 and `arr.length - 1`.\n */\nfunction moveItem(arr, fromIndex, toIndex) {\n asserts.assert(fromIndex >= 0 && fromIndex < arr.length);\n asserts.assert(toIndex >= 0 && toIndex < arr.length);\n // Remove 1 item at fromIndex.\n const 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}\nexports.moveItem = moveItem;\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 */\nfunction zip(var_args) {\n if (!arguments.length) {\n return [];\n }\n const result = [];\n let minLen = arguments[0].length;\n for (let i = 1; i < arguments.length; i++) {\n if (arguments[i].length < minLen) {\n minLen = arguments[i].length;\n }\n }\n for (let i = 0; i < minLen; i++) {\n const value = [];\n for (let j = 0; j < arguments.length; j++) {\n value.push(arguments[j][i]);\n }\n result.push(value);\n }\n return result;\n}\nexports.zip = zip;\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 */\nfunction shuffle(arr, opt_randFn) {\n const randFn = opt_randFn || Math.random;\n\n for (let i = arr.length - 1; i > 0; i--) {\n // Choose a random array index in [0, i] (inclusive with i).\n const j = Math.floor(randFn() * (i + 1));\n\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n}\nexports.shuffle = shuffle;\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 */\nfunction copyByIndex(arr, index_arr) {\n const result = [];\n forEach(index_arr, function(index) {\n result.push(arr[index]);\n });\n return result;\n}\nexports.copyByIndex = copyByIndex;\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 */\nfunction concatMap(arr, f, opt_obj) {\n return concat.apply([], map(arr, f, opt_obj));\n}\nexports.concatMap = concatMap;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A base class for event objects.\n */\n\n\ngoog.provide('goog.events.Event');\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 base class for event objects, so that they can support preventDefault and\n * stopPropagation.\n *\n * @param {string|!goog.events.EventId} type Event Type.\n * @param {Object=} opt_target Reference to the object that is the target of\n * this event. It has to implement the `EventTarget` interface\n * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.\n * @constructor\n */\ngoog.events.Event = function(type, opt_target) {\n 'use strict';\n /**\n * Event type.\n * @type {string}\n */\n this.type = type instanceof goog.events.EventId ? String(type) : type;\n\n /**\n * TODO(tbreisacher): The type should probably be\n * EventTarget|goog.events.EventTarget.\n *\n * Target of the event.\n * @type {Object|undefined}\n */\n this.target = opt_target;\n\n /**\n * Object that had the listener attached.\n * @type {Object|undefined}\n */\n this.currentTarget = this.target;\n\n /**\n * Whether to cancel the event in internal capture/bubble processing for IE.\n * @type {boolean}\n * @private\n */\n this.propagationStopped_ = false;\n\n /**\n * Whether the default action has been prevented.\n * This is a property to match the W3C specification at\n * {@link http://www.w3.org/TR/DOM-Level-3-Events/\n * #events-event-type-defaultPrevented}.\n * Must be treated as read-only outside the class.\n * @type {boolean}\n */\n this.defaultPrevented = false;\n};\n\n/**\n * @return {boolean} true iff internal propagation has been stopped.\n */\ngoog.events.Event.prototype.hasPropagationStopped = function() {\n 'use strict';\n return this.propagationStopped_;\n};\n\n/**\n * Stops event propagation.\n * @return {void}\n */\ngoog.events.Event.prototype.stopPropagation = function() {\n 'use strict';\n this.propagationStopped_ = true;\n};\n\n\n/**\n * Prevents the default action, for example a link redirecting to a url.\n * @return {void}\n */\ngoog.events.Event.prototype.preventDefault = function() {\n 'use strict';\n this.defaultPrevented = true;\n};\n\n\n/**\n * Stops the propagation of the event. It is equivalent to\n * `e.stopPropagation()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.stopPropagation = function(e) {\n 'use strict';\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 * @return {void}\n */\ngoog.events.Event.preventDefault = function(e) {\n 'use strict';\n e.preventDefault();\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Browser capability checks for the events package.\n */\n\ngoog.module('goog.events.BrowserFeature');\ngoog.module.declareLegacyNamespace();\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 */\nconst purify = (fn) => {\n return ({valueOf: fn}).valueOf();\n};\n\n\n/**\n * Enum of browser capabilities.\n * @enum {boolean}\n */\nexports = {\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: false,\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 const nullFunction = () => {};\n goog.global.addEventListener('test', nullFunction, options);\n goog.global.removeEventListener('test', nullFunction, options);\n } catch (e) {\n }\n\n return passive;\n })\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview String functions called from Closure packages that couldn't\n * depend on each other. Outside Closure, use goog.string function which\n * delegate to these.\n */\n\n\ngoog.provide('goog.string.internal');\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n * @see goog.string.startsWith\n */\ngoog.string.internal.startsWith = function(str, prefix) {\n 'use strict';\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 'use strict';\n const l = str.length - suffix.length;\n return l >= 0 && str.indexOf(suffix, l) == l;\n};\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveStartsWith\n */\ngoog.string.internal.caseInsensitiveStartsWith = function(str, prefix) {\n 'use strict';\n return (\n goog.string.internal.caseInsensitiveCompare(\n prefix, str.slice(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 'use strict';\n return (\n goog.string.internal.caseInsensitiveCompare(\n suffix, str.slice(str.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 'use strict';\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 'use strict';\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 'use strict';\n return str.trim();\n } : function(str) {\n 'use strict';\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 'use strict';\n const test1 = String(str1).toLowerCase();\n const test2 = String(str2).toLowerCase();\n\n if (test1 < test2) {\n return -1;\n } else if (test1 == test2) {\n return 0;\n } else {\n return 1;\n }\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n * @see goog.string.newLineToBr\n */\ngoog.string.internal.newLineToBr = function(str, opt_xml) {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n let order = 0;\n // Trim leading and trailing whitespace and split the versions into\n // subversions.\n const v1Subs = goog.string.internal.trim(String(version1)).split('.');\n const v2Subs = goog.string.internal.trim(String(version2)).split('.');\n const subCount = Math.max(v1Subs.length, v2Subs.length);\n\n // Iterate over the subversions, as long as they appear to be equivalent.\n for (let subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\n let v1Sub = v1Subs[subIdx] || '';\n let v2Sub = v2Subs[subIdx] || '';\n\n do {\n // Split the subversions into pairs of numbers and qualifiers (like 'b').\n // Two different RegExp objects are use to make it clear the code\n // is side-effect free\n const v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\n const v2Comp = /(\\d*)(\\D*)(.*)/.exec(v2Sub) || ['', '', '', ''];\n // Break if there are no more matches.\n if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {\n break;\n }\n\n // Parse the numeric part of the subversion. A missing number is\n // equivalent to 0.\n const v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\n const v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);\n\n // Compare the subversion components. The number has the highest\n // precedence. Next, if the numbers are equal, a subversion without any\n // qualifier is always higher than a subversion with any qualifier. Next,\n // the qualifiers are compared as strings.\n order = goog.string.internal.compareElements_(v1CompNum, v2CompNum) ||\n goog.string.internal.compareElements_(\n v1Comp[2].length == 0, v2Comp[2].length == 0) ||\n goog.string.internal.compareElements_(v1Comp[2], v2Comp[2]);\n // Stop as soon as an inequality is discovered.\n\n v1Sub = v1Comp[3];\n v2Sub = v2Comp[3];\n } while (order == 0);\n }\n\n return order;\n};\n\n\n/**\n * Compares elements of a version number.\n *\n * @param {string|number|boolean} left An element from a version number.\n * @param {string|number|boolean} right An element from a version number.\n *\n * @return {number} 1 if `left` is higher.\n * 0 if arguments are equal.\n * -1 if `right` is higher.\n * @private\n */\ngoog.string.internal.compareElements_ = function(left, right) {\n 'use strict';\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n }\n return 0;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities used by goog.labs.userAgent tools. These functions\n * should not be used outside of goog.labs.userAgent.*.\n *\n */\n\ngoog.module('goog.labs.userAgent.util');\ngoog.module.declareLegacyNamespace();\n\nconst {caseInsensitiveContains, contains} = goog.require('goog.string.internal');\nconst {useClientHints} = goog.require('goog.labs.userAgent');\n\n/**\n * @const {boolean} If true, use navigator.userAgentData without check.\n * TODO(user): FEATURESET_YEAR >= 2024 if it supports mobile and all the\n * brands we need. See https://caniuse.com/mdn-api_navigator_useragentdata.\n */\nconst ASSUME_CLIENT_HINTS_SUPPORT = false;\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 */\nfunction getNativeUserAgentString() {\n const navigator = getNavigator();\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n}\n\n/**\n * Gets the native userAgentData object from navigator if it exists.\n * If navigator.userAgentData object is missing returns null.\n * @return {?NavigatorUAData}\n */\nfunction getNativeUserAgentData() {\n const navigator = getNavigator();\n // TODO(user): Use navigator?.userAgent ?? null once it's supported.\n if (navigator) {\n return navigator.userAgentData || null;\n }\n return null;\n}\n\n/**\n * Getter for the native navigator.\n * @return {!Navigator}\n */\nfunction getNavigator() {\n return goog.global.navigator;\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 * @type {?string}\n */\nlet userAgentInternal = null;\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgentData but use a specified value for detection instead.\n * @type {?NavigatorUAData}\n */\nlet userAgentDataInternal = getNativeUserAgentData();\n\n/**\n * Override the user agent string with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to use the native browser object instead.\n * @param {?string=} userAgent The userAgent override.\n * @return {void}\n */\nfunction setUserAgent(userAgent = undefined) {\n userAgentInternal =\n typeof userAgent === 'string' ? userAgent : getNativeUserAgentString();\n}\n\n/** @return {string} The user agent string. */\nfunction getUserAgent() {\n return userAgentInternal == null ? getNativeUserAgentString() :\n userAgentInternal;\n}\n\n/**\n * Override the user agent data object with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to specify the absence of userAgentData. Note that this behavior\n * is different from setUserAgent.\n * @param {?NavigatorUAData} userAgentData The userAgentData override.\n */\nfunction setUserAgentData(userAgentData) {\n userAgentDataInternal = userAgentData;\n}\n\n/**\n * If the user agent data object was overridden using setUserAgentData,\n * reset it so that it uses the native browser object instead, if it exists.\n */\nfunction resetUserAgentData() {\n userAgentDataInternal = getNativeUserAgentData();\n}\n\n/** @return {?NavigatorUAData} Navigator.userAgentData if exist */\nfunction getUserAgentData() {\n return userAgentDataInternal;\n}\n\n/**\n * Checks if any string in userAgentData.brands matches str.\n * Returns false if userAgentData is not supported.\n * @param {string} str\n * @return {boolean} Whether any brand string from userAgentData contains the\n * given string.\n */\nfunction matchUserAgentDataBrand(str) {\n if (!useClientHints()) return false;\n const data = getUserAgentData();\n if (!data) return false;\n return data.brands.some(({brand}) => brand && contains(brand, str));\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string.\n */\nfunction matchUserAgent(str) {\n const userAgent = getUserAgent();\n return contains(userAgent, str);\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string, ignoring\n * case.\n */\nfunction matchUserAgentIgnoreCase(str) {\n const userAgent = getUserAgent();\n return caseInsensitiveContains(userAgent, str);\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 of\n * the parenthetical.\n */\nfunction extractVersionTuples(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 const versionRegExp = new RegExp(\n // Key. Note that a key may have a space.\n // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')\n '([A-Z][\\\\w ]+)' +\n\n '/' + // slash\n '([^\\\\s]+)' + // version (i.e. '5.0b')\n '\\\\s*' + // whitespace\n '(?:\\\\((.*?)\\\\))?', // parenthetical info. parentheses not matched.\n 'g');\n\n const data = [];\n let 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\nexports = {\n ASSUME_CLIENT_HINTS_SUPPORT,\n extractVersionTuples,\n getNativeUserAgentString,\n getUserAgent,\n getUserAgentData,\n matchUserAgent,\n matchUserAgentDataBrand,\n matchUserAgentIgnoreCase,\n resetUserAgentData,\n setUserAgent,\n setUserAgentData,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Useful compiler idioms.\n */\n\ngoog.provide('goog.reflect');\n\n\n/**\n * Syntax for object literal casts.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an object literal whose keys need to have the same names\n * as the properties of some class even after they are renamed by the compiler.\n *\n * @param {!Function} type Type to cast to.\n * @param {Object} object Object literal to cast.\n * @return {Object} The object literal.\n */\ngoog.reflect.object = function(type, object) {\n 'use strict';\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 'use strict';\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 'use strict';\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[' '] = function() {};\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 'use strict';\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 'use strict';\n const storedKey = opt_keyFn ? opt_keyFn(key) : key;\n\n if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\n return cacheObj[storedKey];\n }\n\n return (cacheObj[storedKey] = valueFn(key));\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Rendering engine detection.\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For information on the browser brand (such as Safari versus Chrome), see\n * goog.userAgent.product.\n * @see ../demos/useragent.html\n */\n\ngoog.provide('goog.userAgent');\n\ngoog.require('goog.labs.userAgent.browser');\ngoog.require('goog.labs.userAgent.engine');\ngoog.require('goog.labs.userAgent.platform');\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.reflect');\ngoog.require('goog.string.internal');\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 'use strict';\n return goog.labs.userAgent.util.getUserAgent();\n};\n\n\n/**\n * @return {?Navigator} The native navigator object.\n */\ngoog.userAgent.getNavigatorTyped = function() {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 Android.\n */\ngoog.userAgent.ASSUME_ANDROID =\n goog.define('goog.userAgent.ASSUME_ANDROID', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPhone.\n */\ngoog.userAgent.ASSUME_IPHONE =\n goog.define('goog.userAgent.ASSUME_IPHONE', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPad.\n */\ngoog.userAgent.ASSUME_IPAD = goog.define('goog.userAgent.ASSUME_IPAD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPod.\n */\ngoog.userAgent.ASSUME_IPOD = goog.define('goog.userAgent.ASSUME_IPOD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on KaiOS.\n */\ngoog.userAgent.ASSUME_KAIOS = goog.define('goog.userAgent.ASSUME_KAIOS', false);\n\n\n/**\n * @type {boolean}\n * @private\n */\ngoog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||\n goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||\n goog.userAgent.ASSUME_ANDROID || goog.userAgent.ASSUME_IPHONE ||\n goog.userAgent.ASSUME_IPAD || 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 'use strict';\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 * Whether the user agent is running on Android.\n * @type {boolean}\n */\ngoog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_ANDROID :\n goog.labs.userAgent.platform.isAndroid();\n\n\n/**\n * Whether the user agent is running on an iPhone.\n * @type {boolean}\n */\ngoog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPHONE :\n goog.labs.userAgent.platform.isIphone();\n\n\n/**\n * Whether the user agent is running on an iPad.\n * @type {boolean}\n */\ngoog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPAD :\n goog.labs.userAgent.platform.isIpad();\n\n\n/**\n * Whether the user agent is running on an iPod.\n * @type {boolean}\n */\ngoog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPOD :\n goog.labs.userAgent.platform.isIpod();\n\n\n/**\n * Whether the user agent is running on iOS.\n * @type {boolean}\n */\ngoog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?\n (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD) :\n goog.labs.userAgent.platform.isIos();\n\n/**\n * Whether the user agent is running on KaiOS.\n * @type {boolean}\n */\ngoog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_KAIOS :\n goog.labs.userAgent.platform.isKaiOS();\n\n\n/**\n * @return {string} The string that describes the version number of the user\n * agent.\n * @private\n */\ngoog.userAgent.determineVersion_ = function() {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n return goog.string.internal.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 'use strict';\n return goog.userAgent.ASSUME_ANY_VERSION ||\n goog.reflect.cache(\n goog.userAgent.isVersionOrHigherCache_, version, function() {\n 'use strict';\n return goog.string.internal.compareVersions(\n goog.userAgent.VERSION, version) >= 0;\n });\n};\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 'use strict';\n return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;\n};\n\n\n/**\n * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`.\n * @param {number} version The version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n * @deprecated Use goog.userAgent.isDocumentModeOrHigher().\n */\ngoog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;\n\n\n/**\n * For IE version < 7, documentMode is undefined, so attempt to use the\n * CSS1Compat property to see if we are in standards mode. If we are in\n * standards mode, treat the browser version as the document mode. Otherwise,\n * IE is emulating version 5.\n *\n * NOTE(user): Support for IE < 7 is long gone, so this is now simplified.\n * It returns document.documentMode for IE and undefined for everything else.\n *\n * @type {number|undefined}\n * @const\n */\ngoog.userAgent.DOCUMENT_MODE = (function() {\n 'use strict';\n var doc = goog.global['document'];\n if (!doc || !goog.userAgent.IE) return undefined;\n // This must be an IE user agent.\n var documentMode = goog.userAgent.getDocumentMode_();\n if (documentMode) return documentMode;\n // The user agent version string begins with the major version.\n // Parse the major version and truncate anything following.\n var ieVersion = parseInt(goog.userAgent.VERSION, 10);\n return ieVersion || undefined;\n})();\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection (Browser).\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For more information on rendering engine, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,\n * goog.labs.userAgent.device respectively.)\n */\n\ngoog.module('goog.labs.userAgent.browser');\ngoog.module.declareLegacyNamespace();\n\nconst util = goog.require('goog.labs.userAgent.util');\nconst {AsyncValue, Version} = goog.require('goog.labs.userAgent.highEntropy.highEntropyValue');\nconst {ChromiumRebrand} = goog.require('goog.labs.userAgent.chromiumRebrands');\nconst {assert, assertExists} = goog.require('goog.asserts');\nconst {compareVersions} = goog.require('goog.string.internal');\nconst {fullVersionList} = goog.require('goog.labs.userAgent.highEntropy.highEntropyData');\nconst {useClientHints} = goog.require('goog.labs.userAgent');\n\n// TODO(nnaze): Refactor to remove excessive exclusion logic in matching\n// functions.\n\n/**\n * A browser brand represents an opaque string that is used for making\n * brand-specific version checks in userAgentData.\n * @enum {string}\n */\nconst Brand = {\n /**\n * The browser brand for Android Browser.\n * Do not depend on the value of this string. Because Android Browser has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n ANDROID_BROWSER: 'Android Browser',\n /**\n * The browser brand for Chromium, including Chromium-based Edge and Opera.\n */\n CHROMIUM: 'Chromium',\n /**\n * The browser brand for Edge.\n * This brand can be used to get the version of both EdgeHTML and\n * Chromium-based Edge.\n */\n EDGE: 'Microsoft Edge',\n /**\n * The browser brand for Firefox.\n * Do not depend on the value of this string. Because Firefox has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n FIREFOX: 'Firefox',\n /**\n * The browser brand for Internet Explorer.\n * Do not depend on the value of this string. Because IE will never support\n * userAgentData, the value of this string should be treated as opaque (it's\n * used internally for legacy-userAgent fallback).\n */\n IE: 'Internet Explorer',\n /**\n * The browser brand for Opera.\n * This brand can be used to get the version of both Presto- and\n * Chromium-based Opera.\n */\n OPERA: 'Opera',\n /**\n * The browser brand for Safari.\n * Do not depend on the value of this string. Because Safari has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n SAFARI: 'Safari',\n /**\n * The browser brand for Silk.\n * See\n * https://docs.aws.amazon.com/silk/latest/developerguide/what-is-silk.html\n * Do not depend on the value of this string. Because Silk does not\n * identify itself in userAgentData yet, the value of this string is not\n * guaranteed to stay the same in future revisions.\n */\n SILK: 'Silk',\n};\nexports.Brand = Brand;\n\n/** @typedef {(!Brand|!ChromiumRebrand)} */\nlet AllBrandsInternal;\n\n/**\n * All possible valid values to pass to various UACH Brand-accepting functions.\n * @typedef {(!Brand|!ChromiumRebrand)}\n */\nexports.AllBrands;\n\n/**\n * @param {boolean=} ignoreClientHintsFlag Iff truthy, the `useClientHints`\n * function will not be called when evaluating if User-Agent Client Hints\n * Brand data can be used. For existing labs.userAgent API surfaces with\n * widespread use, this should be a falsy value so that usage of the Client\n * Hints APIs can be gated behind flags / experiment rollouts.\n * @return {boolean} Whether to use navigator.userAgentData to determine\n * browser's brand.\n */\nfunction useUserAgentDataBrand(ignoreClientHintsFlag = false) {\n if (util.ASSUME_CLIENT_HINTS_SUPPORT) return true;\n // High-entropy API surfaces should not be gated behind the useClientHints\n // check (as in production it is gated behind a define).\n if (!ignoreClientHintsFlag && !useClientHints()) return false;\n const userAgentData = util.getUserAgentData();\n return !!userAgentData && userAgentData.brands.length > 0;\n}\n\n/**\n * @return {boolean} Whether this browser is likely to have the fullVersionList\n * high-entropy Client Hint.\n */\nfunction hasFullVersionList() {\n // https://chromiumdash.appspot.com/commits?commit=1eb643c3057e64ff4d22468432ad16c4cab12879&platform=Linux\n // indicates that for all platforms Chromium 98 shipped this feature.\n // See also\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA-Full-Version-List#browser_compatibility\n return isAtLeast(Brand.CHROMIUM, 98);\n}\n\n/**\n * @return {boolean} Whether the user's browser is Opera. Note: Chromium based\n * Opera (Opera 15+) is detected as Chrome to avoid unnecessary special\n * casing.\n */\nfunction matchOpera() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Opera');\n}\n\n/** @return {boolean} Whether the user's browser is IE. */\nfunction matchIE() {\n if (useUserAgentDataBrand()) {\n // IE doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the user's browser is Edge. This refers to\n * EdgeHTML based Edge.\n */\nfunction matchEdgeHtml() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Edge');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nfunction matchEdgeChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.EDGE);\n }\n return util.matchUserAgent('Edg/');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nfunction matchOperaChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.OPERA);\n }\n return util.matchUserAgent('OPR');\n}\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nfunction matchFirefox() {\n // Firefox doesn't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Firefox') || util.matchUserAgent('FxiOS');\n}\n\n/** @return {boolean} Whether the user's browser is Safari. */\nfunction matchSafari() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Safari') &&\n !(matchChrome() || matchCoast() || matchOpera() || matchEdgeHtml() ||\n matchEdgeChromium() || matchOperaChromium() || matchFirefox() ||\n isSilk() || util.matchUserAgent('Android'));\n}\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nfunction matchCoast() {\n if (useUserAgentDataBrand()) {\n // Coast doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Coast');\n}\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nfunction matchIosWebview() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n // iOS Webview does not show up as Chrome or Safari.\n return (util.matchUserAgent('iPad') || util.matchUserAgent('iPhone')) &&\n !matchSafari() && !matchChrome() && !matchCoast() && !matchFirefox() &&\n util.matchUserAgent('AppleWebKit');\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 */\nfunction matchChrome() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.CHROMIUM);\n }\n return ((util.matchUserAgent('Chrome') || util.matchUserAgent('CriOS')) &&\n !matchEdgeHtml()) ||\n isSilk();\n}\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nfunction matchAndroidBrowser() {\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 util.matchUserAgent('Android') &&\n !(isChrome() || isFirefox() || isOpera() || isSilk());\n}\n\n/** @return {boolean} Whether the user's browser is Opera. */\nconst isOpera = matchOpera;\nexports.isOpera = isOpera;\n\n/** @return {boolean} Whether the user's browser is IE. */\nconst isIE = matchIE;\nexports.isIE = isIE;\n\n/** @return {boolean} Whether the user's browser is EdgeHTML based Edge. */\nconst isEdge = matchEdgeHtml;\nexports.isEdge = isEdge;\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nconst isEdgeChromium = matchEdgeChromium;\nexports.isEdgeChromium = isEdgeChromium;\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nconst isOperaChromium = matchOperaChromium;\nexports.isOperaChromium = isOperaChromium;\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nconst isFirefox = matchFirefox;\nexports.isFirefox = isFirefox;\n\n/** @return {boolean} Whether the user's browser is Safari. */\nconst isSafari = matchSafari;\nexports.isSafari = isSafari;\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nconst isCoast = matchCoast;\nexports.isCoast = isCoast;\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nconst isIosWebview = matchIosWebview;\nexports.isIosWebview = isIosWebview;\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 */\nconst isChrome = matchChrome;\nexports.isChrome = isChrome;\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nconst isAndroidBrowser = matchAndroidBrowser;\nexports.isAndroidBrowser = isAndroidBrowser;\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 */\nfunction isSilk() {\n // As of Silk 93, Silk does not identify itself in userAgentData.brands.\n // When Silk changes this behavior, update this method to call\n // matchUserAgentDataBrand (akin to isChrome, etc.)\n return util.matchUserAgent('Silk');\n}\nexports.isSilk = isSilk;\n\n/**\n * A helper function that returns a function mapping a list of candidate\n * version tuple keys to the first version string present under a key.\n * Ex:\n * <code>\n * // Arg extracted from \"Foo/1.2.3 Bar/0.2021\"\n * const mapVersion = createVersionMap([[\"Foo\", \"1.2.3\"], [\"Bar\", \"0.2021\"]]);\n * mapVersion([\"Bar\", \"Foo\"]); // returns \"0.2021\"\n * mapVersion([\"Baz\", \"Foo\"]); // returns \"1.2.3\"\n * mapVersion([\"Baz\", \"???\"]); // returns \"\"\n * </code>\n * @param {!Array<!Array<string>>} versionTuples Version tuples pre-extracted\n * from a user agent string.\n * @return {function(!Array<string>): string} The version string, or empty\n * string if it doesn't exist under the given key.\n */\nfunction createVersionMap(versionTuples) {\n // Construct a map for easy lookup.\n const versionMap = {};\n versionTuples.forEach((tuple) => {\n // Note that the tuple is of length three, but we only care about the\n // first two.\n const key = tuple[0];\n const value = tuple[1];\n versionMap[key] = value;\n });\n\n // Gives the value with the first key it finds, otherwise empty string.\n return (keys) => versionMap[keys.find((key) => key in versionMap)] || '';\n}\n\n/**\n * Returns the browser version.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and returns the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use\n * getVersionStringForLogging() or fullVersionOf() instead.\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 */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (isIE()) {\n return getIEVersion(userAgentString);\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\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 (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 (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n }\n\n // Check Chromium Edge before Chrome since it has Chrome in the string.\n if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n\n // Check Silk before Chrome since it may have Chrome in its string and be\n // treated as Chrome.\n if (isSilk()) {\n return lookUpValueWithKeys(['Silk']);\n }\n\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n\n // Usually products browser versions are in the third tuple after \"Mozilla\"\n // and the engine.\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n}\nexports.getVersion = getVersion;\n\n/**\n * Returns whether the current browser's version is at least as high as the\n * given one.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and checks the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\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 * @deprecated Use isAtLeast()/isAtMost() instead.\n */\nfunction isVersionOrHigher(version) {\n return compareVersions(getVersion(), version) >= 0;\n}\nexports.isVersionOrHigher = isVersionOrHigher;\n\n/**\n * A helper function to determine 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 * @param {string} userAgent the User-Agent.\n * @return {string}\n */\nfunction getIEVersion(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 const rv = /rv: *([\\d\\.]*)/.exec(userAgent);\n if (rv && rv[1]) {\n return rv[1];\n }\n\n let version = '';\n const 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 const 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\n/**\n * A helper function to return the navigator.userAgent-supplied full version\n * number of the current browser or an empty string, based on whether the\n * current browser is the one specified.\n * @param {string} browser The brand whose version should be returned.\n * @return {string}\n */\nfunction getFullVersionFromUserAgentString(browser) {\n const userAgentString = util.getUserAgent();\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (browser === Brand.IE) {\n return isIE() ? getIEVersion(userAgentString) : '';\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n switch (browser) {\n case Brand.OPERA:\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\"\n // first. Opera uses 'OPR' for more recent UAs.\n if (isOpera()) {\n return lookUpValueWithKeys(['Version', 'Opera']);\n } else if (isOperaChromium()) {\n return lookUpValueWithKeys(['OPR']);\n }\n break;\n case Brand.EDGE:\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n } else if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n break;\n case Brand.CHROMIUM:\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n break;\n }\n\n // For the following browsers, the browser version is in the third tuple after\n // \"Mozilla\" and the engine.\n if ((browser === Brand.FIREFOX && isFirefox()) ||\n (browser === Brand.SAFARI && isSafari()) ||\n (browser === Brand.ANDROID_BROWSER && isAndroidBrowser()) ||\n (browser === Brand.SILK && isSilk())) {\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n }\n\n return '';\n}\n\n/**\n * Returns the major version of the given browser brand, or NaN if the current\n * browser is not the given brand.\n * Note that the major version number may be different depending on which\n * browser is specified. The returned value can be used to make browser version\n * comparisons using comparison operators.\n * @private\n * @param {!AllBrandsInternal} browser The brand whose version should be\n * returned.\n * @return {number} The major version number associated with the current\n * browser under the given brand, or NaN if the current browser doesn't match\n * the given brand.\n */\nfunction versionOf_(browser) {\n let versionParts;\n // Silk currently does not identify itself in its userAgentData.brands array,\n // so if checking its version, always fall back to the user agent string.\n if (useUserAgentDataBrand() && browser !== Brand.SILK) {\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n if (!matchingBrand || !matchingBrand.version) {\n return NaN;\n }\n versionParts = matchingBrand.version.split('.');\n } else {\n const fullVersion = getFullVersionFromUserAgentString(browser);\n if (fullVersion === '') {\n return NaN;\n }\n versionParts = fullVersion.split('.');\n }\n if (versionParts.length === 0) {\n return NaN;\n }\n const majorVersion = versionParts[0];\n return Number(majorVersion); // Returns NaN if it is not parseable.\n}\n\n/**\n * Returns true if the current browser matches the given brand and is at least\n * the given major version. The major version must be a whole number (i.e.\n * decimals should not be used to represent a minor version).\n * @param {!AllBrandsInternal} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at least the given version.\n */\nfunction isAtLeast(brand, majorVersion) {\n assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf_(brand) >= majorVersion;\n}\nexports.isAtLeast = isAtLeast;\n\n/**\n * Returns true if the current browser matches the given brand and is at most\n * the given version. The major version must be a whole number (i.e. decimals\n * should not be used to represent a minor version).\n * @param {!AllBrandsInternal} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at most the given version.\n */\nfunction isAtMost(brand, majorVersion) {\n assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf_(brand) <= majorVersion;\n}\nexports.isAtMost = isAtMost;\n\n/**\n * Loads the high-entropy browser brand/version data and wraps the correct\n * version string in a Version object.\n * @implements {AsyncValue<!Version>}\n */\nclass HighEntropyBrandVersion {\n /**\n * @param {string} brand The brand whose version is retrieved in this\n * container.\n * @param {boolean} useUach Whether to attempt to use the User-Agent Client\n * Hints (UACH) API surface.\n * @param {string} fallbackVersion The fallback version derived from the\n * userAgent string.\n */\n constructor(brand, useUach, fallbackVersion) {\n /** @private @const {string} */\n this.brand_ = brand;\n\n /** @private @const {!Version} */\n this.version_ = new Version(fallbackVersion);\n\n /** @private @const {boolean} */\n this.useUach_ = useUach;\n }\n\n /**\n * @return {!Version|undefined}\n * @override\n */\n getIfLoaded() {\n if (this.useUach_) {\n const loadedVersionList = fullVersionList.getIfLoaded();\n if (loadedVersionList !== undefined) {\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n // We assumed in fullVersionOf that if the fullVersionList is defined\n // the brands must match. Double-check this here.\n assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n // Fallthrough to fallback on Pre-UACH implementation\n }\n // We want to make sure the loading semantics of the Pre-UACH implementation\n // match those of the UACH implementation. Loading must happen before any\n // data can be retrieved from getIfLoaded.\n // For HighEntropyBrandVersion, loading can either be done by calling #load\n // or by calling the module-local loadFullVersions function.\n if (preUachHasLoaded) {\n return this.version_;\n }\n return;\n }\n\n /**\n * @return {!Promise<!Version>}\n * @override\n */\n async load() {\n if (this.useUach_) {\n const loadedVersionList = await fullVersionList.load();\n if (loadedVersionList !== undefined) {\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n // Fallthrough to fallback on Pre-UACH implementation\n } else {\n // Await something so that calling load with or without UACH API\n // availability results in waiting at least one macrotask before allowing\n // access to the cached version information.\n await 0;\n }\n // Regardless of whether we are using UACH APIs, we can now allow access to\n // the fallback case\n preUachHasLoaded = true;\n return this.version_;\n }\n}\n\n/**\n * Whether full version data should be considered available when using UACH\n * fallback implementations. This is flipped to true when either\n * loadFullVersions or HighEntropyBrandVersion.prototype.load are called,\n * matching the global singleton semantics of the UACH codepaths.\n */\nlet preUachHasLoaded = false;\n\n/**\n * Requests all full browser versions to be cached. When the returned promise\n * resolves, subsequent calls to `fullVersionOf(...).getIfLoaded()` will return\n * a value.\n *\n * This method should be avoided in favor of directly awaiting\n * `fullVersionOf(...).load()` where it is used.\n *\n * @return {!Promise<void>}\n */\nasync function loadFullVersions() {\n if (useUserAgentDataBrand(true)) {\n await fullVersionList.load();\n }\n preUachHasLoaded = true;\n}\nexports.loadFullVersions = loadFullVersions;\n\n/**\n * Resets module-local caches used by functionality in this module.\n * This is only for use by goog.labs.userAgent.testUtil.resetUserAgent (and\n * labs.userAgent tests).\n * @package\n */\nexports.resetForTesting = () => {\n preUachHasLoaded = false;\n fullVersionList.resetForTesting();\n};\n\n\n/**\n * Returns an object that provides access to the full version string of the\n * current browser -- or undefined, based on whether the current browser matches\n * the requested browser brand. Note that the full version string is a\n * high-entropy value, and must be asynchronously loaded before it can be\n * accessed synchronously.\n * @param {!AllBrandsInternal} browser The brand whose version should be\n * returned.\n * @return {!AsyncValue<!Version>|undefined} An object that can be used\n * to get or load the full version string as a high-entropy value, or\n * undefined if the current browser doesn't match the given brand.\n */\nfunction fullVersionOf(browser) {\n let fallbackVersionString = '';\n // If we are reasonably certain now that the browser we are on has the\n // fullVersionList high-entropy hint, then we can skip computing the fallback\n // value as we won't end up using it.\n if (!hasFullVersionList()) {\n fallbackVersionString = getFullVersionFromUserAgentString(browser);\n }\n // Silk has the UACH API surface, but currently does not identify itself in\n // the userAgentData.brands array. Fallback to using userAgent string version\n // for Silk.\n const useUach = browser !== Brand.SILK && useUserAgentDataBrand(true);\n if (useUach) {\n const data = util.getUserAgentData();\n // Operate under the assumption that the low-entropy and high-entropy lists\n // of brand/version pairs contain an identical set of brands. Therefore, if\n // the low-entropy list doesn't contain the given brand, return undefined.\n if (!data.brands.find(({brand}) => brand === browser)) {\n return undefined;\n }\n } else if (fallbackVersionString === '') {\n return undefined;\n }\n return new HighEntropyBrandVersion(browser, useUach, fallbackVersionString);\n}\nexports.fullVersionOf = fullVersionOf;\n\n\n/**\n * Returns a version string for the current browser or undefined, based on\n * whether the current browser is the one specified.\n * This value should ONLY be used for logging/debugging purposes. Do not use it\n * to branch code paths. For comparing versions, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n * @param {!AllBrandsInternal} browser The brand whose version should be\n * returned.\n * @return {string} The version as a string.\n */\nfunction getVersionStringForLogging(browser) {\n if (useUserAgentDataBrand(true)) {\n const fullVersionObj = fullVersionOf(browser);\n if (fullVersionObj) {\n const fullVersion = fullVersionObj.getIfLoaded();\n if (fullVersion) {\n return fullVersion.toVersionStringForLogging();\n }\n // No full version, return the major version instead.\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n // Checking for the existence of matchingBrand is not necessary because\n // the existence of fullVersionObj implies that there is already a\n // matching brand.\n assertExists(matchingBrand);\n return matchingBrand.version;\n }\n // If fullVersionObj is undefined, this doesn't mean that the full version\n // is unavailable, but rather that the current browser doesn't match the\n // input `browser` argument.\n return '';\n } else {\n return getFullVersionFromUserAgentString(browser);\n }\n}\nexports.getVersionStringForLogging = getVersionStringForLogging;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection.\n * @see http://en.wikipedia.org/wiki/User_agent\n * For more information on browser brand, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent (browser, platform, and device).\n */\n\ngoog.module('goog.labs.userAgent.engine');\ngoog.module.declareLegacyNamespace();\n\nconst googArray = goog.require('goog.array');\nconst googString = goog.require('goog.string.internal');\nconst util = goog.require('goog.labs.userAgent.util');\n\n/**\n * @return {boolean} Whether the rendering engine is Presto.\n */\nfunction isPresto() {\n return util.matchUserAgent('Presto');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Trident.\n */\nfunction isTrident() {\n // IE only started including the Trident token in IE8.\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is EdgeHTML.\n */\nfunction isEdge() {\n return util.matchUserAgent('Edge');\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 */\nfunction isWebKit() {\n return util.matchUserAgentIgnoreCase('WebKit') && !isEdge();\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Gecko.\n */\nfunction isGecko() {\n return util.matchUserAgent('Gecko') && !isWebKit() && !isTrident() &&\n !isEdge();\n}\n\n/**\n * @return {string} The rendering engine's version or empty string if version\n * can't be determined.\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n if (userAgentString) {\n const tuples = util.extractVersionTuples(userAgentString);\n\n const engineTuple = 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 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 const browserTuple = tuples[0];\n let info;\n if (browserTuple && (info = browserTuple[2])) {\n const match = /Trident\\/([^\\s;]+)/.exec(info);\n if (match) {\n return match[1];\n }\n }\n }\n return '';\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 */\nfunction getEngineTuple(tuples) {\n if (!isEdge()) {\n return tuples[1];\n }\n for (let i = 0; i < tuples.length; i++) {\n const tuple = tuples[i];\n if (tuple[0] == 'Edge') {\n return tuple;\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 */\nfunction isVersionOrHigher(version) {\n return googString.compareVersions(getVersion(), version) >= 0;\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 */\nfunction getVersionForKey(tuples, key) {\n // TODO(nnaze): Move to util if useful elsewhere.\n\n const pair = googArray.find(tuples, function(pair) {\n return key == pair[0];\n });\n\n return pair && pair[1] || '';\n}\n\nexports = {\n getVersion,\n isEdge,\n isGecko,\n isPresto,\n isTrident,\n isVersionOrHigher,\n isWebKit,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A patched, standardized event object for browser events.\n *\n * <pre>\n * The patched event object contains the following members:\n * - type {string} Event type, e.g. 'click'\n * - target {Object} The element that actually triggered the event\n * - currentTarget {Object} The element the listener is attached to\n * - relatedTarget {Object} For mouseover and mouseout, the previous object\n * - offsetX {number} X-coordinate relative to target\n * - offsetY {number} Y-coordinate relative to target\n * - clientX {number} X-coordinate relative to viewport\n * - clientY {number} Y-coordinate relative to viewport\n * - screenX {number} X-coordinate relative to the edge of the screen\n * - screenY {number} Y-coordinate relative to the edge of the screen\n * - button {number} Mouse button. Use isButton() to test.\n * - keyCode {number} Key-code\n * - ctrlKey {boolean} Was ctrl key depressed\n * - altKey {boolean} Was alt key depressed\n * - shiftKey {boolean} Was shift key depressed\n * - metaKey {boolean} Was meta key depressed\n * - pointerId {number} Pointer ID\n * - pointerType {string} Pointer type, e.g. 'mouse', 'pen', or 'touch'\n * - defaultPrevented {boolean} Whether the default action has been prevented\n * - state {Object} History state object\n *\n * NOTE: The keyCode member contains the raw browser keyCode. For normalized\n * key and character code use {@link goog.events.KeyHandler}.\n * </pre>\n */\n\ngoog.provide('goog.events.BrowserEvent');\ngoog.provide('goog.events.BrowserEvent.MouseButton');\ngoog.provide('goog.events.BrowserEvent.PointerType');\n\ngoog.require('goog.debug');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventType');\ngoog.require('goog.reflect');\ngoog.require('goog.userAgent');\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 'use strict';\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 * @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.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY =\n goog.define('goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY', false);\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 BACK: 3,\n FORWARD: 4,\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 'use strict';\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 * @suppress {strictMissingProperties} Added to tighten compiler checks\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.BrowserEvent.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 /** @suppress {strictMissingProperties} Added to tighten compiler checks */\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 /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.pointerId = e.pointerId || 0;\n this.pointerType = goog.events.BrowserEvent.getPointerType_(e);\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.state = e.state;\n this.event_ = e;\n if (e.defaultPrevented) {\n // Sync native event state to internal state via super class, where default\n // prevention is implemented and managed.\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\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 'use strict';\n return this.event_.button == button;\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 'use strict';\n // Ctrl+click should never behave like a left-click on mac, regardless of\n // whether or not the browser will actually ever emit such an event. If\n // we see it, treat it like right-click always.\n return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&\n !(goog.userAgent.MAC && this.ctrlKey);\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.stopPropagation = function() {\n 'use strict';\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 'use strict';\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n var be = this.event_;\n if (!be.preventDefault) {\n be.returnValue = false;\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 'use strict';\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 'use strict';\n if (typeof (e.pointerType) === 'string') {\n return e.pointerType;\n }\n // IE10 uses integer codes for pointer type.\n // https://msdn.microsoft.com/en-us/library/hh772359(v=vs.85).aspx\n return goog.events.BrowserEvent.IE_POINTER_TYPE_MAP[e.pointerType] || '';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.events.EventType');\n\ngoog.require('goog.events.eventTypeHelpers');\ngoog.require('goog.userAgent');\n\n\n/**\n * Constants for event names.\n * @enum {string}\n */\ngoog.events.EventType = {\n // Mouse events\n CLICK: 'click',\n RIGHTCLICK: 'rightclick',\n DBLCLICK: 'dblclick',\n AUXCLICK: 'auxclick',\n MOUSEDOWN: 'mousedown',\n MOUSEUP: 'mouseup',\n MOUSEOVER: 'mouseover',\n MOUSEOUT: 'mouseout',\n MOUSEMOVE: 'mousemove',\n MOUSEENTER: 'mouseenter',\n MOUSELEAVE: 'mouseleave',\n\n // Non-existent event; will never fire. This exists as a mouse counterpart to\n // POINTERCANCEL.\n MOUSECANCEL: 'mousecancel',\n\n // Selection events.\n // https://www.w3.org/TR/selection-api/\n SELECTIONCHANGE: 'selectionchange',\n SELECTSTART: 'selectstart', // IE, Safari, Chrome\n\n // Wheel events\n // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\n WHEEL: 'wheel',\n\n // Key events\n KEYPRESS: 'keypress',\n KEYDOWN: 'keydown',\n KEYUP: 'keyup',\n\n // Focus\n BLUR: 'blur',\n FOCUS: 'focus',\n DEACTIVATE: 'deactivate', // IE only\n FOCUSIN: 'focusin',\n FOCUSOUT: 'focusout',\n\n // Forms\n CHANGE: 'change',\n RESET: 'reset',\n SELECT: 'select',\n SUBMIT: 'submit',\n INPUT: 'input',\n PROPERTYCHANGE: 'propertychange', // IE only\n\n // Drag and drop\n DRAGSTART: 'dragstart',\n DRAG: 'drag',\n DRAGENTER: 'dragenter',\n DRAGOVER: 'dragover',\n DRAGLEAVE: 'dragleave',\n DROP: 'drop',\n DRAGEND: 'dragend',\n\n // Touch events\n // Note that other touch events exist, but we should follow the W3C list here.\n // http://www.w3.org/TR/touch-events/#list-of-touchevent-types\n TOUCHSTART: 'touchstart',\n TOUCHMOVE: 'touchmove',\n TOUCHEND: 'touchend',\n TOUCHCANCEL: 'touchcancel',\n\n // Misc\n BEFOREUNLOAD: 'beforeunload',\n CONSOLEMESSAGE: 'consolemessage',\n CONTEXTMENU: 'contextmenu',\n DEVICECHANGE: 'devicechange',\n DEVICEMOTION: 'devicemotion',\n DEVICEORIENTATION: 'deviceorientation',\n DOMCONTENTLOADED: 'DOMContentLoaded',\n ERROR: 'error',\n HELP: 'help',\n LOAD: 'load',\n LOSECAPTURE: 'losecapture',\n ORIENTATIONCHANGE: 'orientationchange',\n READYSTATECHANGE: 'readystatechange',\n RESIZE: 'resize',\n SCROLL: 'scroll',\n UNLOAD: 'unload',\n\n // Media events\n CANPLAY: 'canplay',\n CANPLAYTHROUGH: 'canplaythrough',\n DURATIONCHANGE: 'durationchange',\n EMPTIED: 'emptied',\n ENDED: 'ended',\n LOADEDDATA: 'loadeddata',\n LOADEDMETADATA: 'loadedmetadata',\n PAUSE: 'pause',\n PLAY: 'play',\n PLAYING: 'playing',\n PROGRESS: 'progress',\n RATECHANGE: 'ratechange',\n SEEKED: 'seeked',\n SEEKING: 'seeking',\n STALLED: 'stalled',\n SUSPEND: 'suspend',\n TIMEUPDATE: 'timeupdate',\n VOLUMECHANGE: 'volumechange',\n WAITING: 'waiting',\n\n // Media Source Extensions events\n // https://www.w3.org/TR/media-source/#mediasource-events\n SOURCEOPEN: 'sourceopen',\n SOURCEENDED: 'sourceended',\n SOURCECLOSED: 'sourceclosed',\n // https://www.w3.org/TR/media-source/#sourcebuffer-events\n ABORT: 'abort',\n UPDATE: 'update',\n UPDATESTART: 'updatestart',\n UPDATEEND: 'updateend',\n\n // HTML 5 History events\n // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0\n HASHCHANGE: 'hashchange',\n PAGEHIDE: 'pagehide',\n PAGESHOW: 'pageshow',\n POPSTATE: 'popstate',\n\n // Copy and Paste\n // Support is limited. Make sure it works on your favorite browser\n // before using.\n // http://www.quirksmode.org/dom/events/cutcopypaste.html\n COPY: 'copy',\n PASTE: 'paste',\n CUT: 'cut',\n BEFORECOPY: 'beforecopy',\n BEFORECUT: 'beforecut',\n BEFOREPASTE: 'beforepaste',\n\n // HTML5 online/offline events.\n // http://www.w3.org/TR/offline-webapps/#related\n ONLINE: 'online',\n OFFLINE: 'offline',\n\n // HTML 5 worker events\n MESSAGE: 'message',\n CONNECT: 'connect',\n\n // Service Worker Events - ServiceWorkerGlobalScope context\n // See https://w3c.github.io/ServiceWorker/#execution-context-events\n // Note: message event defined in worker events section\n INSTALL: 'install',\n ACTIVATE: 'activate',\n FETCH: 'fetch',\n FOREIGNFETCH: 'foreignfetch',\n MESSAGEERROR: 'messageerror',\n\n // Service Worker Events - Document context\n // See https://w3c.github.io/ServiceWorker/#document-context-events\n STATECHANGE: 'statechange',\n UPDATEFOUND: 'updatefound',\n CONTROLLERCHANGE: 'controllerchange',\n\n // CSS animation events.\n ANIMATIONSTART:\n goog.events.eventTypeHelpers.getVendorPrefixedName('AnimationStart'),\n ANIMATIONEND:\n goog.events.eventTypeHelpers.getVendorPrefixedName('AnimationEnd'),\n ANIMATIONITERATION:\n goog.events.eventTypeHelpers.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 TRANSITIONEND:\n goog.events.eventTypeHelpers.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 // Fullscreen API events. See https://fullscreen.spec.whatwg.org/.\n FULLSCREENCHANGE: 'fullscreenchange',\n // iOS-only fullscreen events. See\n // https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/ControllingMediaWithJavaScript/ControllingMediaWithJavaScript.html\n WEBKITBEGINFULLSCREEN: 'webkitbeginfullscreen',\n WEBKITENDFULLSCREEN: 'webkitendfullscreen',\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 // Print events.\n BEFOREPRINT: 'beforeprint',\n AFTERPRINT: 'afterprint',\n\n // Web app manifest events.\n BEFOREINSTALLPROMPT: 'beforeinstallprompt',\n APPINSTALLED: 'appinstalled',\n\n // Web Animation API (WAAPI) playback events\n // https://www.w3.org/TR/web-animations-1/#animation-playback-event-types\n CANCEL: 'cancel',\n FINISH: 'finish',\n REMOVE: 'remove'\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface for a listenable JavaScript object.\n */\n\ngoog.provide('goog.events.Listenable');\n\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\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 'use strict';\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 'use strict';\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 = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\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 = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\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 = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\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 = function(key) {};\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 = function(e) {};\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|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.Listenable.prototype.removeAllListeners = function(opt_type) {};\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 = function() {};\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 = function(\n type, capture, eventObject) {};\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 = function(type, capture) {};\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 = function(\n type, listener, capture, opt_listenerScope) {};\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 = function(\n opt_type, opt_capture) {};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface that describes a single registered listener.\n */\ngoog.provide('goog.events.ListenableKey');\n\ngoog.requireType('goog.events.Listenable');\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 'use strict';\n return ++goog.events.ListenableKey.counter_;\n};\n\n\n/**\n * The source event target.\n * @type {?Object|?goog.events.Listenable}\n */\ngoog.events.ListenableKey.prototype.src;\n\n\n/**\n * The event type the listener is listening to.\n * @type {string}\n */\ngoog.events.ListenableKey.prototype.type;\n\n\n/**\n * The listener function.\n * @type {function(?):?|{handleEvent:function(?):?}|null}\n */\ngoog.events.ListenableKey.prototype.listener;\n\n\n/**\n * Whether the listener works on capture phase.\n * @type {boolean}\n */\ngoog.events.ListenableKey.prototype.capture;\n\n\n/**\n * The 'this' object for the listener function's scope.\n * @type {?Object|undefined}\n */\ngoog.events.ListenableKey.prototype.handler;\n\n\n/**\n * A globally unique number to identify the key.\n * @type {number}\n */\ngoog.events.ListenableKey.prototype.key;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Listener object.\n * @see ../demos/events.html\n */\n\ngoog.provide('goog.events.Listener');\n\ngoog.require('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listenable');\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 'use strict';\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 'use strict';\n this.removed = true;\n this.listener = null;\n this.proxy = null;\n this.src = null;\n this.handler = null;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A map of listeners that provides utility functions to\n * deal with listeners on an event target. Used by\n * `goog.events.EventTarget`.\n *\n * WARNING: Do not use this class from outside goog.events package.\n *\n */\n\ngoog.provide('goog.events.ListenerMap');\n\ngoog.require('goog.array');\ngoog.require('goog.events.Listener');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.Listenable');\ngoog.requireType('goog.events.ListenableKey');\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 'use strict';\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 'use strict';\n return this.typeCount_;\n};\n\n\n/**\n * @return {number} Total number of registered listeners.\n */\ngoog.events.ListenerMap.prototype.getListenerCount = function() {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n var hasType = (opt_type !== undefined);\n var typeStr = hasType ? opt_type.toString() : '';\n var hasCapture = (opt_capture !== undefined);\n\n return goog.object.some(this.listeners, function(listenerArray, type) {\n 'use strict';\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 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (!listenerObj.removed && listenerObj.listener == listener &&\n listenerObj.capture == !!opt_useCapture &&\n listenerObj.handler == opt_listenerScope) {\n return i;\n }\n }\n return -1;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating objects/maps/hashes.\n */\ngoog.module('goog.object');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls a function for each element in an object/map/hash.\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 for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and the return value is ignored.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {void}\n * @template T,K,V\n */\nfunction forEach(obj, f, opt_obj) {\n for (const key in obj) {\n f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n}\n\n/**\n * 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 * @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 for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) 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 element is not\n * 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 */\nfunction filter(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n res[key] = obj[key];\n }\n }\n return res;\n}\n\n/**\n * For every element in an object/map/hash calls a function and inserts the\n * result into a new object.\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 for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and should return something. The result will be inserted into a\n * 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 */\nfunction map(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n return res;\n}\n\n/**\n * 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 * @param {?Object<K,V>} obj The object to check.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should 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 */\nfunction some(obj, f, opt_obj) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * 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 * @param {?Object<K,V>} obj The object to check.\n * @param {?function(this:T,V,?,?Object<K,V>):boolean} f The function to call\n * for every element. This function takes 3 arguments (the value, the key\n * and the object) and should 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 */\nfunction every(obj, f, opt_obj) {\n for (const key in obj) {\n if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns the number of key-value pairs in the object map.\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 */\nfunction getCount(obj) {\n let rv = 0;\n for (const key in obj) {\n rv++;\n }\n return rv;\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 * @param {?Object} obj The object to pick a key from.\n * @return {string|undefined} The key or undefined if the object is empty.\n */\nfunction getAnyKey(obj) {\n for (const key in obj) {\n return key;\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 * @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 */\nfunction getAnyValue(obj) {\n for (const key in obj) {\n return obj[key];\n }\n}\n\n/**\n * Whether the object/hash/map contains the given object as a value.\n * An alias for containsValue(obj, val).\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 */\nfunction contains(obj, val) {\n return containsValue(obj, val);\n}\n\n/**\n * Returns the values of the object/map/hash.\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 */\nfunction getValues(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = obj[key];\n }\n return res;\n}\n\n/**\n * Returns the keys of the object/map/hash.\n * @param {?Object} obj The object from which to get the keys.\n * @return {!Array<string>} Array of property keys.\n */\nfunction getKeys(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = key;\n }\n return res;\n}\n\n/**\n * 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 * @param {?Object} obj An object to get the value from. Can be array-like.\n * @param {...(string|number|!IArrayLike<number|string>)} var_args A number of\n * keys (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 in the\n * current object is null or undefined, returns undefined.\n */\nfunction getValueByKeys(obj, var_args) {\n const isArrayLike = goog.isArrayLike(var_args);\n const keys = isArrayLike ?\n /** @type {!IArrayLike<number|string>} */ (var_args) :\n arguments;\n\n // Start with the 2nd parameter for the variable parameters syntax.\n for (let i = isArrayLike ? 0 : 1; i < keys.length; i++) {\n if (obj == null) return undefined;\n obj = obj[keys[i]];\n }\n\n return obj;\n}\n\n/**\n * Whether the object/map/hash contains the given key.\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 */\nfunction containsKey(obj, key) {\n return obj !== null && key in obj;\n}\n\n/**\n * Whether the object/map/hash contains the given value. This is O(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 */\nfunction containsValue(obj, val) {\n for (const key in obj) {\n if (obj[key] == val) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * 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 function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj 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 */\nfunction findKey(obj, f, thisObj = undefined) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (thisObj), obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\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 to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj 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 */\nfunction findValue(obj, f, thisObj = undefined) {\n const key = findKey(obj, f, thisObj);\n return key && obj[key];\n}\n\n/**\n * Whether the object/map/hash is empty.\n * @param {?Object} obj The object to test.\n * @return {boolean} true if obj is empty.\n */\nfunction isEmpty(obj) {\n for (const key in obj) {\n return false;\n }\n return true;\n}\n\n/**\n * Removes all key value pairs from the object/map/hash.\n * @param {?Object} obj The object to clear.\n * @return {void}\n */\nfunction clear(obj) {\n for (const i in obj) {\n delete obj[i];\n }\n}\n\n/**\n * Removes a key-value pair based on the key.\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 */\nfunction remove(obj, key) {\n let rv;\n if (rv = key in /** @type {!Object} */ (obj)) {\n delete obj[key];\n }\n return rv;\n}\n\n/**\n * 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 * @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 * @return {void}\n * @template K,V\n */\nfunction add(obj, key, val) {\n if (obj !== null && key in obj) {\n throw new Error(`The object already contains the key \"${key}\"`);\n }\n set(obj, key, val);\n}\n\n/**\n * Returns the value for the given key.\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=} val The value to return if no item is found for the given key\n * (default is undefined).\n * @return {V|R|undefined} The value for the given key.\n * @template K,V,R\n */\nfunction get(obj, key, val = undefined) {\n if (obj !== null && key in obj) {\n return obj[key];\n }\n return val;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash.\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 * @return {void}\n */\nfunction set(obj, key, value) {\n obj[key] = value;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash if it doesn't exist yet.\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 */\nfunction setIfUndefined(obj, key, value) {\n return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);\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 * This function is particularly useful when used with an `Object` which is\n * acting as a cache.\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 */\nfunction setWithReturnValueIfNotSet(obj, key, f) {\n if (key in obj) {\n return obj[key];\n }\n\n const val = f();\n obj[key] = val;\n return val;\n}\n\n/**\n * Compares two objects for equality using === on the values.\n * @param {!Object<K,V>} a\n * @param {!Object<K,V>} b\n * @return {boolean}\n * @template K,V\n */\nfunction equals(a, b) {\n for (const k in a) {\n if (!(k in b) || a[k] !== b[k]) {\n return false;\n }\n }\n for (const k in b) {\n if (!(k in a)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns a shallow clone of the object.\n * @param {?Object<K,V>} obj Object to clone.\n * @return {!Object<K,V>} Clone of the input object.\n * @template K,V\n */\nfunction clone(obj) {\n const res = {};\n for (const key in obj) {\n res[key] = obj[key];\n }\n return res;\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 * WARNINGS:\n * <code>unsafeClone</code> does not detect reference loops. Objects\n * that refer to themselves will cause infinite recursion.\n * <code>unsafeClone</code> is unaware of unique identifiers, and\n * copies UIDs created by <code>getUid</code> into cloned results.\n * @param {T} obj The value to clone.\n * @return {T} A clone of the input value.\n * @template T\n */\nfunction unsafeClone(obj) {\n if (!obj || typeof obj !== 'object') return obj;\n if (typeof obj.clone === 'function') return obj.clone();\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n } else if (obj instanceof Date) {\n return new Date(obj.getTime());\n }\n const clone = Array.isArray(obj) ? [] :\n typeof ArrayBuffer === 'function' &&\n typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(obj) &&\n !(obj instanceof DataView) ?\n new obj.constructor(obj.length) :\n {};\n for (const key in obj) {\n clone[key] = unsafeClone(obj[key]);\n }\n return clone;\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 * @param {?Object} obj The object to transpose.\n * @return {!Object} The transposed object.\n */\nfunction transpose(obj) {\n const transposed = {};\n for (const key in obj) {\n transposed[obj[key]] = key;\n }\n return transposed;\n}\n\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n */\nconst PROTOTYPE_FIELDS = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf',\n];\n\n/**\n * Extends an object with another object.\n * This operates 'in-place'; it does not create a new Object.\n * Example:\n * var o = {};\n * extend(o, {a: 0, b: 1});\n * o; // {a: 0, b: 1}\n * extend(o, {b: 2, c: 3});\n * o; // {a: 0, b: 2, c: 3}\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 `var_args`.\n * @param {...(?Object|undefined)} var_args The objects from which values\n * will be copied.\n * @return {void}\n * @deprecated Prefer Object.assign\n */\nfunction extend(target, var_args) {\n let key;\n let source;\n for (let i = 1; i < arguments.length; i++) {\n source = arguments[i];\n for (key in source) {\n target[key] = source[key];\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n\n for (let j = 0; j < PROTOTYPE_FIELDS.length; j++) {\n key = PROTOTYPE_FIELDS[j];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\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 */\nfunction create(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return create.apply(null, arguments[0]);\n }\n\n if (argLength % 2) {\n throw new Error('Uneven number of arguments');\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i += 2) {\n rv[arguments[i]] = arguments[i + 1];\n }\n return rv;\n}\n\n/**\n * 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 as\n * the property names.\n * @return {!Object} The new object.\n */\nfunction createSet(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return createSet.apply(null, arguments[0]);\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i++) {\n rv[arguments[i]] = true;\n }\n return rv;\n}\n\n/**\n * Creates an immutable view of the underlying object, if the browser\n * supports immutable objects.\n * In default mode, writes to this view will fail silently. In strict mode,\n * they will throw an error.\n * @param {!Object<K,V>} obj An object.\n * @return {!Object<K,V>} An immutable view of that object, or the original\n * object if this browser does not support immutables.\n * @template K,V\n */\nfunction createImmutableView(obj) {\n let result = obj;\n if (Object.isFrozen && !Object.isFrozen(obj)) {\n result = Object.create(obj);\n Object.freeze(result);\n }\n return result;\n}\n\n/**\n * @param {!Object} obj An object.\n * @return {boolean} Whether this is an immutable view of the object.\n */\nfunction isImmutableView(obj) {\n return !!Object.isFrozen && Object.isFrozen(obj);\n}\n\n/**\n * Get all properties names on a given Object regardless of enumerability.\n * <p> If the browser does not support `Object.getOwnPropertyNames` nor\n * `Object.getPrototypeOf` then this is equivalent to using\n * `getKeys`\n * @param {?Object} obj The object to get the properties of.\n * @param {boolean=} includeObjectPrototype Whether properties defined on\n * `Object.prototype` should be included in the result.\n * @param {boolean=} includeFunctionPrototype Whether properties defined on\n * `Function.prototype` should be included in the result.\n * @return {!Array<string>}\n * @public\n */\nfunction getAllPropertyNames(\n obj, includeObjectPrototype = undefined,\n includeFunctionPrototype = undefined) {\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 getKeys(obj);\n }\n\n const visitedSet = {};\n\n // Traverse the prototype chain and add all properties to the visited set.\n let proto = obj;\n while (proto && (proto !== Object.prototype || !!includeObjectPrototype) &&\n (proto !== Function.prototype || !!includeFunctionPrototype)) {\n const names = Object.getOwnPropertyNames(proto);\n for (let i = 0; i < names.length; i++) {\n visitedSet[names[i]] = true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n\n return getKeys(visitedSet);\n}\n\n/**\n * Given a ES5 or ES6 class reference, return its super class / super\n * constructor.\n * This should be used in rare cases where you need to walk up the inheritance\n * tree (this is generally a bad idea). But this work with ES5 and ES6 classes,\n * unlike relying on the superClass_ property.\n * Note: To start walking up the hierarchy from an instance call this with its\n * `constructor` property; e.g. `getSuperClass(instance.constructor)`.\n * @param {function(new: ?)} constructor\n * @return {?Object}\n */\nfunction getSuperClass(constructor) {\n const proto = Object.getPrototypeOf(constructor.prototype);\n return proto && proto.constructor;\n}\n\nexports = {\n add,\n clear,\n clone,\n contains,\n containsKey,\n containsValue,\n create,\n createImmutableView,\n createSet,\n equals,\n every,\n extend,\n filter,\n findKey,\n findValue,\n forEach,\n get,\n getAllPropertyNames,\n getAnyKey,\n getAnyValue,\n getCount,\n getKeys,\n getSuperClass,\n getValueByKeys,\n getValues,\n isEmpty,\n isImmutableView,\n map,\n remove,\n set,\n setIfUndefined,\n setWithReturnValueIfNotSet,\n some,\n transpose,\n unsafeClone,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An event manager for both native browser event\n * targets and custom JavaScript event targets\n * (`goog.events.Listenable`). This provides an abstraction\n * over browsers' event systems.\n *\n * It also provides a simulation of W3C event model's capture phase in\n * Internet Explorer (IE 8 and below). Caveat: the simulation does not\n * interact well with listeners registered directly on the elements\n * (bypassing goog.events) or even with listeners registered via\n * goog.events in a separate JS binary. In these cases, we provide\n * no ordering guarantees.\n *\n * The listeners will receive a \"patched\" event object. Such event object\n * contains normalized values for certain event properties that differs in\n * different browsers.\n *\n * Example usage:\n * <pre>\n * goog.events.listen(myNode, 'click', function(e) { alert('woo') });\n * goog.events.listen(myNode, 'mouseover', mouseHandler, true);\n * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);\n * goog.events.removeAll(myNode);\n * </pre>\n *\n * in IE and event object patching]\n *\n * @see ../demos/events.html\n * @see ../demos/event-propagation.html\n * @see ../demos/stopevent.html\n */\n\n// IMPLEMENTATION NOTES:\n// goog.events stores an auxiliary data structure on each EventTarget\n// source being listened on. This allows us to take advantage of GC,\n// having the data structure GC'd when the EventTarget is GC'd. This\n// GC behavior is equivalent to using W3C DOM Events directly.\n\ngoog.provide('goog.events');\ngoog.provide('goog.events.CaptureSimulationMode');\ngoog.provide('goog.events.Key');\ngoog.provide('goog.events.ListenableType');\n\ngoog.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');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.EventWrapper');\ngoog.requireType('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listener');\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 * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listen = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (opt_options && opt_options.once) {\n return goog.events.listenOnce(\n src, type, listener, opt_options, opt_handler);\n }\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listen(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listen(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ false, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target. A listener can only be added once to an object and if it\n * is added again the key for the listener is returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {EventTarget} src The node to listen to events on.\n * @param {string|?goog.events.EventId<EVENTOBJ>} type Event type.\n * @param {!Function} listener Callback function.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener or otherwise.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} Unique key for the listener.\n * @template EVENTOBJ\n * @private\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listen_ = function(\n src, type, listener, callOnce, opt_options, opt_handler) {\n 'use strict';\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\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 /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n proxy.src = src;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n proxy.listener = listenerObj;\n\n // Attach the proxy through the browser's API\n if (src.addEventListener) {\n // Don't pass an object as `capture` if the browser doesn't support that.\n if (!goog.events.BrowserFeature.PASSIVE_EVENTS) {\n opt_options = capture;\n }\n // Don't break tests that expect a boolean.\n if (opt_options === undefined) opt_options = false;\n src.addEventListener(type.toString(), proxy, opt_options);\n } else if (src.attachEvent) {\n // The else if above used to be an unconditional else. It would call\n // attachEvent come gws or high water. This would sometimes throw an\n // exception on IE11, spoiling the day of some callers. The previous\n // incarnation of this code, from 2007, indicates that it replaced an\n // earlier still version that caused excess allocations on IE6.\n src.attachEvent(goog.events.getOnString_(type.toString()), proxy);\n } else if (src.addListener && src.removeListener) {\n // In IE, MediaQueryList uses addListener() insteadd of addEventListener. In\n // Safari, there is no global for the MediaQueryList constructor, so we just\n // check whether the object \"looks like\" MediaQueryList.\n goog.asserts.assert(\n type === 'change', 'MediaQueryList only has a change event');\n src.addListener(proxy);\n } else {\n throw new Error('addEventListener and attachEvent are unavailable.');\n }\n\n goog.events.listenerCountEstimate_++;\n return listenerObj;\n};\n\n\n/**\n * Helper function for returning a proxy function.\n * @return {!Function} A new or reused function object.\n */\ngoog.events.getProxy = function() {\n 'use strict';\n const proxyCallbackFunction = goog.events.handleBrowserEvent_;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n const f = function(eventObject) {\n return proxyCallbackFunction.call(f.src, f.listener, eventObject);\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 * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.listenOnce = function(\n src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listenOnce(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listenOnce(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ true, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.Listenable}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.Listenable} src The target to\n * listen to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @template T\n */\ngoog.events.listenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\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 * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.unlisten = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.unlisten(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.unlisten(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return false;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n var listenerObj = listenerMap.getListener(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n if (listenerObj) {\n return goog.events.unlistenByKey(listenerObj);\n }\n }\n\n return false;\n};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {goog.events.Key} key The key returned by listen() for this\n * event listener.\n * @return {boolean} indicating whether the listener was there to remove.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.unlistenByKey = function(key) {\n 'use strict';\n // TODO(chrishenry): Remove this check when tests that rely on this\n // are fixed.\n if (typeof key === 'number') {\n return false;\n }\n\n var listener = key;\n if (!listener || listener.removed) {\n return false;\n }\n\n var src = listener.src;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return /** @type {!goog.events.Listenable} */ (src).unlistenByKey(listener);\n }\n\n var type = listener.type;\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\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 'use strict';\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 'use strict';\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 'use strict';\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 * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {\n 'use strict';\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 * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.hasListener = function(obj, opt_type, opt_capture) {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.fireListener = function(listener, eventObject) {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n if (listener.removed) {\n return true;\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.events.wrapListener = function(listener) {\n 'use strict';\n goog.asserts.assert(listener, 'Listener can not be null.');\n\n if (typeof listener === 'function') {\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 'use strict';\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 'use strict';\n goog.events.handleBrowserEvent_ =\n transformer(goog.events.handleBrowserEvent_);\n });\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A disposable implementation of a custom\n * listenable/event target. See also: documentation for\n * `goog.events.Listenable`.\n *\n * @see ../demos/eventtarget.html\n * @see goog.events.Listenable\n */\n\ngoog.provide('goog.events.EventTarget');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.asserts');\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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|!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 `#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 'use strict';\n goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\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 * @override\n */\ngoog.events.EventTarget.prototype.dispatchEvent = function(e) {\n 'use strict';\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 'use strict';\n goog.events.EventTarget.superClass_.disposeInternal.call(this);\n\n this.removeAllListeners();\n this.parentEventTarget_ = null;\n};\n\n\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 * @override\n */\ngoog.events.EventTarget.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n this.assertInitialized_();\n return this.eventTargetListeners_.add(\n String(type), listener, false /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\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 * @override\n */\ngoog.events.EventTarget.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.add(\n String(type), listener, true /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\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 * @override\n */\ngoog.events.EventTarget.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.remove(\n String(type), listener, opt_useCapture, opt_listenerScope);\n};\n\n\n/**\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n * @override\n */\ngoog.events.EventTarget.prototype.unlistenByKey = function(key) {\n 'use strict';\n return this.eventTargetListeners_.removeByKey(key);\n};\n\n\n/**\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n * @override\n */\ngoog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {\n 'use strict';\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/**\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 * @override\n */\ngoog.events.EventTarget.prototype.fireListeners = function(\n type, capture, eventObject) {\n 'use strict';\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // getListeners(type, capture) instead, which is simpler.\n var listenerArray = this.eventTargetListeners_.listeners[String(type)];\n if (!listenerArray) {\n return true;\n }\n listenerArray = listenerArray.concat();\n\n var rv = true;\n for (var i = 0; i < listenerArray.length; ++i) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && !listener.removed && listener.capture == capture) {\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n this.unlistenByKey(listener);\n }\n rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;\n }\n }\n\n return rv && !eventObject.defaultPrevented;\n};\n\n\n/**\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 * @override\n */\ngoog.events.EventTarget.prototype.getListeners = function(type, capture) {\n 'use strict';\n return this.eventTargetListeners_.getListeners(String(type), capture);\n};\n\n\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 * @override\n */\ngoog.events.EventTarget.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.getListener(\n String(type), listener, capture, opt_listenerScope);\n};\n\n\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 * @override\n */\ngoog.events.EventTarget.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var id = (opt_type !== undefined) ? String(opt_type) : undefined;\n return this.eventTargetListeners_.hasListener(id, opt_capture);\n};\n\n\n/**\n * Sets the target to be used for `event.target` when firing\n * event. Mainly used for testing. For example, see\n * `goog.testing.events.mixinListenable`.\n * @param {!Object} target The target.\n */\ngoog.events.EventTarget.prototype.setTargetForTesting = function(target) {\n 'use strict';\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 'use strict';\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 'use strict';\n /** @suppress {missingProperties} */\n var type = e.type || /** @type {string} */ (e);\n\n // If accepting a string or object, create a custom event object so that\n // preventDefault and stopPropagation work with the event.\n if (typeof e === 'string') {\n e = new goog.events.Event(e, target);\n } else if (!(e instanceof goog.events.Event)) {\n var oldEvent = e;\n e = new goog.events.Event(type, target);\n goog.object.extend(e, oldEvent);\n } else {\n e.target = e.target || target;\n }\n\n var rv = true, currentTarget;\n\n // Executes all capture listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (var i = opt_ancestorsTree.length - 1;\n !e.hasPropagationStopped() && i >= 0; i--) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, true, e) && rv;\n }\n }\n\n // Executes capture and bubble listeners on the target.\n if (!e.hasPropagationStopped()) {\n currentTarget = /** @type {?} */ (e.currentTarget = target);\n rv = currentTarget.fireListeners(type, true, e) && rv;\n if (!e.hasPropagationStopped()) {\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n // Executes all bubble listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (i = 0; !e.hasPropagationStopped() && i < opt_ancestorsTree.length;\n i++) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n return rv;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview JSON utility functions.\n */\n\n\ngoog.provide('goog.json');\ngoog.provide('goog.json.Replacer');\ngoog.provide('goog.json.Reviver');\ngoog.provide('goog.json.Serializer');\n\n\n/**\n * @define {boolean} If true, use the native JSON parsing API.\n * NOTE: The default `goog.json.parse` implementation is able to handle\n * invalid JSON. JSPB used to produce invalid JSON which is not the case\n * anymore so this is safe to enable for parsing JSPB. Using native JSON is\n * faster and safer than the default implementation using `eval`.\n */\ngoog.json.USE_NATIVE_JSON = goog.define('goog.json.USE_NATIVE_JSON', false);\n\n\n/**\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 'use strict';\n // All empty whitespace is not valid.\n if (/^\\s*$/.test(s)) {\n return false;\n }\n\n // This is taken from http://www.json.org/json2.js which is released to the\n // public domain.\n // Changes: We dissallow \\u2028 Line separator and \\u2029 Paragraph separator\n // inside strings. We also treat \\u2028 and \\u2029 as whitespace which they\n // are in the RFC but IE and Safari does not match \\s to these so we need to\n // include them in the reg exps in all places where whitespace is allowed.\n // We allowed \\x7f inside strings because some tools don't escape it,\n // e.g. http://www.json.org/java/org/json/JSONObject.java\n\n // Parsing happens in three stages. In the first stage, we run the text\n // against regular expressions that look for non-JSON patterns. We are\n // especially concerned with '()' and 'new' because they can cause invocation,\n // and '=' because it can cause mutation. But just to be safe, we want to\n // reject all unexpected forms.\n\n // We split the first stage into 4 regexp operations in order to work around\n // crippling inefficiencies in IE's and Safari's regexp engines. First we\n // replace all backslash pairs with '@' (a non-JSON character). Second, we\n // replace all simple value tokens with ']' characters, but only when followed\n // by a colon, comma, closing bracket or end of string. Third, we delete all\n // open brackets that follow a colon or comma or that begin the text. Finally,\n // we look to see that the remaining characters are only whitespace or ']' or\n // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.\n\n // Don't make these static since they have the global flag.\n const backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\n const simpleValuesRe =\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\n const openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\n const remainderRe = /^[\\],:{}\\s\\u2028\\u2029]*$/;\n\n return remainderRe.test(\n s.replace(backslashesRe, '@')\n .replace(simpleValuesRe, ']')\n .replace(openBracketsRe, ''));\n};\n\n/**\n * Logs a parsing error in `JSON.parse` solvable by using `eval`.\n * @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_ = () => {};\n\n\n/**\n * Sets an error logger to use if there's a recoverable parsing error.\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 'use strict';\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 'use strict';\n let error;\n try {\n return goog.global['JSON']['parse'](s);\n } catch (ex) {\n error = ex;\n }\n const o = String(s);\n if (goog.json.isValid(o)) {\n\n try {\n const result = /** @type {?Object} */ (eval('(' + o + ')'));\n if (error) {\n goog.json.errorLogger_('Invalid JSON: ' + o, error);\n }\n return result;\n } catch (ex) {\n }\n }\n throw new Error('Invalid JSON string: ' + o);\n };\n\n\n/**\n * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * TODO(nicksantos): Array should also be a valid replacer.\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Replacer;\n\n\n/**\n * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Reviver;\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @param {?goog.json.Replacer=} opt_replacer A replacer function\n * called for each (key, value) pair that determines how the value\n * should be serialized. By defult, this just returns the value\n * and allows default serialization to kick in.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.serialize = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*, ?goog.json.Replacer=):string} */\n (goog.global['JSON']['stringify']) :\n function(object, opt_replacer) {\n 'use strict';\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 'use strict';\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 'use strict';\n const sb = [];\n this.serializeInternal(object, sb);\n return sb.join('');\n};\n\n\n/**\n * Serializes a generic value to a JSON string\n * @protected\n * @param {*} object The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @throws Error if there are loops in the object graph.\n */\ngoog.json.Serializer.prototype.serializeInternal = function(object, sb) {\n 'use strict';\n if (object == null) {\n // undefined == null so this branch covers undefined as well as null\n sb.push('null');\n return;\n }\n\n if (typeof object == 'object') {\n if (Array.isArray(object)) {\n this.serializeArray(object, sb);\n return;\n } else if (\n object instanceof String || object instanceof Number ||\n object instanceof Boolean) {\n object = object.valueOf();\n // Fall through to switch below.\n } else {\n this.serializeObject_(/** @type {!Object} */ (object), sb);\n return;\n }\n }\n\n switch (typeof object) {\n case 'string':\n this.serializeString_(object, sb);\n break;\n case 'number':\n this.serializeNumber_(object, sb);\n break;\n case 'boolean':\n sb.push(String(object));\n break;\n case 'function':\n sb.push('null');\n break;\n default:\n throw new Error('Unknown type: ' + typeof object);\n }\n};\n\n\n/**\n * Character mappings used internally for goog.string.quote\n * @private\n * @type {!Object}\n */\ngoog.json.Serializer.charToJsonCharCache_ = {\n '\\\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '/': '\\\\/',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n\n '\\x0B': '\\\\u000b' // '\\v' is not supported in JScript\n};\n\n\n/**\n * Regular expression used to match characters that need to be replaced.\n * The S60 browser has a bug where unicode characters are not matched by\n * regular expressions. The condition below detects such behaviour and\n * adjusts the regular expression accordingly.\n * @private\n * @type {!RegExp}\n */\ngoog.json.Serializer.charsToReplace_ = /\\uffff/.test('\\uffff') ?\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g :\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\n\n\n/**\n * Serializes a string to a JSON string\n * @private\n * @param {string} s The string to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeString_ = function(s, sb) {\n 'use strict';\n // The official JSON implementation does not work with international\n // characters.\n sb.push('\"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {\n 'use strict';\n // caching the result improves performance by a factor 2-3\n let rv = goog.json.Serializer.charToJsonCharCache_[c];\n if (!rv) {\n rv = '\\\\u' + (c.charCodeAt(0) | 0x10000).toString(16).slice(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 'use strict';\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 'use strict';\n const l = arr.length;\n sb.push('[');\n let sep = '';\n for (let i = 0; i < l; i++) {\n sb.push(sep);\n\n const value = arr[i];\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,\n sb);\n\n sep = ',';\n }\n sb.push(']');\n};\n\n\n/**\n * Serializes an object to a JSON string\n * @private\n * @param {!Object} obj The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {\n 'use strict';\n sb.push('{');\n let sep = '';\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n // Skip functions.\n if (typeof value != 'function') {\n sb.push(sep);\n this.serializeString_(key, sb);\n sb.push(':');\n\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);\n\n sep = ',';\n }\n }\n }\n sb.push('}');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.module('goog.async.WorkQueue');\ngoog.module.declareLegacyNamespace();\n\nconst FreeList = goog.require('goog.async.FreeList');\nconst {assert} = goog.require('goog.asserts');\n\n// TODO(johnlenz): generalize the WorkQueue if this is used by more\n// than goog.async.run.\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 * @final\n * @struct\n */\nclass WorkQueue {\n constructor() {\n this.workHead_ = null;\n this.workTail_ = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n add(fn, scope) {\n const 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 assert(!this.workHead_);\n this.workHead_ = item;\n this.workTail_ = item;\n }\n }\n\n /**\n * @return {?WorkItem}\n */\n remove() {\n let 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 * @param {!WorkItem} item\n */\n returnUnused(item) {\n WorkQueue.freelist_.put(item);\n }\n\n /**\n * @return {!WorkItem}\n * @private\n */\n getUnusedItem_() {\n return WorkQueue.freelist_.get();\n }\n}\n\n/** @define {number} The maximum number of entries to keep for recycling. */\nWorkQueue.DEFAULT_MAX_UNUSED =\n goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);\n\n/** @const @private {!FreeList<!WorkItem>} */\nWorkQueue.freelist_ = new FreeList(\n () => new WorkItem(), item => item.reset(), WorkQueue.DEFAULT_MAX_UNUSED);\n\n/**\n * @final\n * @struct\n */\nclass WorkItem {\n constructor() {\n /** @type {?function()} */\n this.fn = null;\n /** @type {?Object|null|undefined} */\n this.scope = null;\n /** @type {?WorkItem} */\n this.next = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n set(fn, scope) {\n this.fn = fn;\n this.scope = scope;\n this.next = null;\n }\n\n /** Reset the work item so they don't prevent GC before reuse */\n reset() {\n this.fn = null;\n this.scope = null;\n this.next = null;\n }\n}\n\nexports = WorkQueue;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple freelist.\n *\n * An anterative to goog.structs.SimplePool, it imposes the requirement that the\n * objects in the list contain a \"next\" property that can be used to maintain\n * the pool.\n */\ngoog.module('goog.async.FreeList');\ngoog.module.declareLegacyNamespace();\n\n/** @template ITEM */\nclass FreeList {\n /**\n * @param {function():ITEM} create\n * @param {function(ITEM):void} reset\n * @param {number} limit\n */\n constructor(create, reset, limit) {\n /** @private @const {number} */\n this.limit_ = limit;\n /** @private @const {function()} */\n this.create_ = create;\n /** @private @const {function(ITEM):void} */\n this.reset_ = reset;\n\n /** @private {number} */\n this.occupants_ = 0;\n /** @private {ITEM} */\n this.head_ = null;\n }\n\n /** @return {ITEM} */\n get() {\n let item;\n if (this.occupants_ > 0) {\n this.occupants_--;\n item = this.head_;\n this.head_ = item.next;\n item.next = null;\n } else {\n item = this.create_();\n }\n return item;\n }\n\n /** @param {ITEM} item An item available for possible future reuse. */\n put(item) {\n this.reset_(item);\n if (this.occupants_ < this.limit_) {\n this.occupants_++;\n item.next = this.head_;\n this.head_ = item;\n }\n }\n\n /**\n * Visible for testing.\n * @return {number}\n * @package\n */\n occupants() {\n return this.occupants_;\n }\n}\n\nexports = FreeList;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\ngoog.module('goog.async.run');\ngoog.module.declareLegacyNamespace();\n\nconst WorkQueue = goog.require('goog.async.WorkQueue');\nconst asyncStackTag = goog.require('goog.debug.asyncStackTag');\nconst nextTick = goog.require('goog.async.nextTick');\nconst throwException = goog.require('goog.async.throwException');\n\n/**\n * @define {boolean} If true, use the global Promise to implement 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 * The function used to schedule work asynchronousely.\n * @private {function()}\n */\nlet schedule;\n\n/** @private {boolean} */\nlet workQueueScheduled = false;\n\n/** @type {!WorkQueue} */\nlet workQueue = new WorkQueue();\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=} context Object to use as the \"this value\" when calling the\n * provided function.\n * @template THIS\n */\nlet run = (callback, context = undefined) => {\n if (!schedule) {\n initializeRunner();\n }\n if (!workQueueScheduled) {\n // Nothing is currently scheduled, schedule it now.\n schedule();\n workQueueScheduled = true;\n }\n callback = asyncStackTag.wrap(callback, 'goog.async.run');\n\n workQueue.add(callback, context);\n};\n\n/** Initializes the function to use to process the work queue. */\nlet initializeRunner = () => {\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 const promise = goog.global.Promise.resolve(undefined);\n schedule = () => {\n promise.then(run.processWorkQueue);\n };\n } else {\n schedule = () => {\n nextTick(run.processWorkQueue);\n };\n }\n};\n\n/**\n * Forces run to use nextTick instead of Promise.\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 * 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 * @param {function(function())=} realSetTimeout\n */\nrun.forceNextTick = (realSetTimeout = undefined) => {\n schedule = () => {\n nextTick(run.processWorkQueue);\n if (realSetTimeout) {\n realSetTimeout(run.processWorkQueue);\n }\n };\n};\n\nif (goog.DEBUG) {\n /** Reset the work queue. Only available for tests in debug mode. */\n run.resetQueue = () => {\n workQueueScheduled = false;\n workQueue = new WorkQueue();\n };\n\n /** Resets the scheduler. Only available for tests in debug mode. */\n run.resetSchedulerForTest = () => {\n initializeRunner();\n };\n}\n\n/**\n * Run any pending 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 * nextTick.\n */\nrun.processWorkQueue = () => {\n // NOTE: additional work queue items may be added while processing.\n let item = null;\n while (item = workQueue.remove()) {\n try {\n item.fn.call(item.scope);\n } catch (e) {\n throwException(e);\n }\n workQueue.returnUnused(item);\n }\n\n // There are no more work items, allow processing to be scheduled again.\n workQueueScheduled = false;\n};\n\nexports = run;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a function to throw an error without interrupting\n * the current execution context.\n */\n\ngoog.module('goog.async.throwException');\ngoog.module.declareLegacyNamespace();\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 */\nfunction throwException(exception) {\n // Each throw needs to be in its own context.\n goog.global.setTimeout(() => {\n throw exception;\n }, 0);\n}\nexports = throwException;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A timer class to which other classes and objects can listen on.\n * This is only an abstraction above `setInterval`.\n *\n * @see ../demos/timers.html\n */\n\ngoog.provide('goog.Timer');\n\ngoog.require('goog.Promise');\ngoog.require('goog.events.EventTarget');\ngoog.requireType('goog.Thenable');\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n this.dispatchEvent(goog.Timer.TICK);\n};\n\n\n/**\n * Starts the timer.\n */\ngoog.Timer.prototype.start = function() {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n if (typeof listener === 'function') {\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 'use strict';\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 'use strict';\n var timerKey = null;\n return new goog\n .Promise(function(resolve, reject) {\n 'use strict';\n timerKey = goog.Timer.callOnce(function() {\n 'use strict';\n resolve(opt_result);\n }, delay);\n if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {\n reject(new Error('Failed to schedule timer.'));\n }\n })\n .thenCatch(function(error) {\n 'use strict';\n // Clear the timer. The most likely reason is \"cancel\" signal.\n goog.Timer.clear(timerKey);\n throw error;\n });\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the goog.async.Throttle class.\n *\n * @see ../demos/timers.html\n */\n\ngoog.module('goog.async.Throttle');\ngoog.module.declareLegacyNamespace();\n\nconst Disposable = goog.require('goog.Disposable');\nconst Timer = goog.require('goog.Timer');\n\n\n/**\n * Throttle will perform an action that is passed in no more than once\n * per interval (specified in milliseconds). If it gets multiple signals\n * to perform the action while it is waiting, it will only perform the action\n * once at the end of the interval.\n * @final\n * @template T\n */\nclass Throttle extends Disposable {\n /**\n * @param {function(this: T, ...?)} listener Function to callback when the\n * action is triggered.\n * @param {number} interval Interval over which to throttle. The listener can\n * only be called once per interval.\n * @param {T=} handler Object in whose scope to call the listener.\n */\n constructor(listener, interval, handler) {\n super();\n /**\n * Function to callback\n * @type {function(this: T, ...?)}\n * @private\n */\n this.listener_ = handler != null ? listener.bind(handler) : listener;\n\n /**\n * Interval for the throttle time\n * @type {number}\n * @private\n */\n this.interval_ = interval;\n\n /**\n * The last arguments passed into `fire`, or null if there is no pending\n * call.\n * @private {?IArrayLike}\n */\n this.args_ = null;\n\n /**\n * Indicates that the action is pending and needs to be fired.\n * @type {boolean}\n * @private\n */\n this.shouldFire_ = false;\n\n /**\n * Indicates the count of nested pauses currently in effect on the throttle.\n * When this count is not zero, fired actions will be postponed until the\n * throttle is resumed enough times to drop the pause count to zero.\n * @type {number}\n * @private\n */\n this.pauseCount_ = 0;\n\n /**\n * Timer for scheduling the next callback\n * @type {?number}\n * @private\n */\n this.timer_ = null;\n }\n\n /**\n * Notifies the throttle that the action has happened. It will throttle\n * the call so that the callback is not called too often according to the\n * interval parameter passed to the constructor, passing the arguments\n * from the last call of this function into the throttled function.\n * @param {...?} var_args Arguments to pass on to the throttled function.\n */\n fire(var_args) {\n this.args_ = arguments;\n if (!this.timer_ && !this.pauseCount_) {\n this.doAction_();\n } else {\n this.shouldFire_ = true;\n }\n }\n\n /**\n * Cancels any pending action callback. The throttle can be restarted by\n * calling {@link #fire}.\n */\n stop() {\n if (this.timer_) {\n Timer.clear(this.timer_);\n this.timer_ = null;\n this.shouldFire_ = false;\n this.args_ = null;\n }\n }\n\n /**\n * Pauses the throttle. All pending and future action callbacks will be\n * delayed until the throttle is resumed. Pauses can be nested.\n */\n pause() {\n this.pauseCount_++;\n }\n\n /**\n * Resumes the throttle. If doing so drops the pausing count to zero,\n * pending action callbacks will be executed as soon as possible, but\n * still no sooner than an interval's delay after the previous call.\n * Future action callbacks will be executed as normal.\n */\n resume() {\n this.pauseCount_--;\n if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /** @override */\n disposeInternal() {\n super.disposeInternal();\n this.stop();\n }\n\n /**\n * Handler for the timer to fire the throttle\n * @private\n */\n onTimer_() {\n this.timer_ = null;\n\n if (this.shouldFire_ && !this.pauseCount_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /**\n * Calls the callback\n * @private\n */\n doAction_() {\n this.timer_ = Timer.callOnce(() => this.onTimer_(), this.interval_);\n const args = this.args_;\n // release memory first so it always happens even if listener throws\n this.args_ = null;\n this.listener_.apply(null, args);\n }\n}\n\nexports = Throttle;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class to create objects which want to handle multiple events\n * and have their listeners easily cleaned up via a dispose method.\n *\n * Example:\n * <pre>\n * function Something() {\n * Something.base(this);\n *\n * ... set up object ...\n *\n * // Add event listeners\n * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar);\n * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand);\n * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover);\n * }\n * goog.inherits(Something, goog.events.EventHandler);\n *\n * Something.prototype.disposeInternal = function() {\n * Something.base(this, 'disposeInternal');\n * goog.dom.removeNode(this.container);\n * };\n *\n *\n * // Then elsewhere:\n *\n * var activeSomething = null;\n * function openSomething() {\n * activeSomething = new Something();\n * }\n *\n * function closeSomething() {\n * if (activeSomething) {\n * activeSomething.dispose(); // Remove event listeners\n * activeSomething = null;\n * }\n * }\n * </pre>\n */\n\ngoog.provide('goog.events.EventHandler');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.events');\ngoog.require('goog.object');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventTarget');\ngoog.requireType('goog.events.EventWrapper');\n\n\n\n/**\n * Super class for objects that want to easily manage a number of event\n * listeners. It allows a short cut to listen and also provides a quick way\n * to remove all events listeners belonging to this object.\n * @param {SCOPE=} opt_scope Object in whose scope to call the listeners.\n * @constructor\n * @extends {goog.Disposable}\n * @template SCOPE\n */\ngoog.events.EventHandler = function(opt_scope) {\n 'use strict';\n goog.Disposable.call(this);\n // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3\n // that access this private variable. :(\n this.handler_ = opt_scope;\n\n /**\n * Keys for events that are being listened to.\n * @type {!Object<!goog.events.Key>}\n * @private\n */\n this.keys_ = {};\n};\ngoog.inherits(goog.events.EventHandler, goog.Disposable);\n\n\n/**\n * Utility array used to unify the cases of listening for an array of types\n * and listening for a single event, without using recursion or allocating\n * an array each time.\n * @type {!Array<string>}\n * @const\n * @private\n */\ngoog.events.EventHandler.typeArray_ = [];\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listen = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listen_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|!AddEventListenerOptions|undefined} options\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenWithScope = function(\n src, type, fn, options, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listen_(src, type, fn, options, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listen_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (!Array.isArray(type)) {\n if (type) {\n goog.events.EventHandler.typeArray_[0] = type.toString();\n }\n type = goog.events.EventHandler.typeArray_;\n }\n for (var i = 0; i < type.length; i++) {\n var listenerObj = goog.events.listen(\n src, type[i], opt_fn || self.handleEvent, opt_options || false,\n opt_scope || self.handler_ || self);\n\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnce = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listenOnce_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnceWithScope = function(\n src, type, fn, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenOnce_(src, type, fn, capture, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired\n * the event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenOnce_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.listenOnce_(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var listenerObj = goog.events.listenOnce(\n src, type, opt_fn || self.handleEvent, opt_options,\n opt_scope || self.handler_ || self);\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\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.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:SCOPE, ?):?|{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 * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapper = function(\n src, wrapper, listener, opt_capt) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Remove the opt_scope from this function and then\n // templatize it.\n return self.listenWithWrapper_(src, wrapper, listener, opt_capt);\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.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null}\n * listener Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapperAndScope = function(\n src, wrapper, listener, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenWithWrapper_(src, wrapper, listener, capture, scope);\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.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener Callback\n * 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 {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenWithWrapper_ = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.listen(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * @return {number} Number of listeners registered by this handler.\n */\ngoog.events.EventHandler.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var key in this.keys_) {\n if (Object.prototype.hasOwnProperty.call(this.keys_, key)) {\n count++;\n }\n }\n return count;\n};\n\n\n/**\n * Unlistens on an event.\n * @param {goog.events.ListenableType} src Event source.\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(this:?, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.unlisten = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.unlisten(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n var listener = goog.events.getListener(\n src, type, opt_fn || self.handleEvent, capture,\n opt_scope || self.handler_ || self);\n\n if (listener) {\n goog.events.unlistenByKey(listener);\n delete self.keys_[listener.key];\n }\n }\n\n return self;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.EventTarget} 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_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.unlisten(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * Unlistens to all events.\n */\ngoog.events.EventHandler.prototype.removeAll = function() {\n 'use strict';\n goog.object.forEach(this.keys_, function(listenerObj, key) {\n 'use strict';\n if (this.keys_.hasOwnProperty(key)) {\n goog.events.unlistenByKey(listenerObj);\n }\n }, this);\n\n this.keys_ = {};\n};\n\n\n/**\n * Disposes of this EventHandler and removes all listeners that it registered.\n * @override\n * @protected\n */\ngoog.events.EventHandler.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventHandler.superClass_.disposeInternal.call(this);\n this.removeAll();\n};\n\n\n/**\n * Default event handler\n * @param {goog.events.Event} e Event object.\n */\ngoog.events.EventHandler.prototype.handleEvent = function(e) {\n 'use strict';\n throw new Error('EventHandler.handleEvent not implemented');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a utility for tracing and debugging WebChannel\n * requests.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.require('goog.json');\ngoog.require('goog.log');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.net.XmlHttp.ReadyState');\n\n\n\n/**\n * Logs and keeps a buffer of debugging info for the Channel.\n *\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.WebChannelDebug = function() {\n 'use strict';\n /**\n * The logger instance.\n * @const\n * @private {?goog.log.Logger}\n */\n this.logger_ = goog.log.getLogger('goog.labs.net.webChannel.WebChannelDebug');\n\n /**\n * Whether to enable redact. Defaults to true.\n * @private {boolean}\n */\n this.redactEnabled_ = true;\n};\n\n\ngoog.scope(function() {\n'use strict';\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Turns off redact.\n */\nWebChannelDebug.prototype.disableRedact = function() {\n 'use strict';\n this.redactEnabled_ = false;\n};\n\n\n/**\n * Logs that the browser went offline during the lifetime of a request.\n * @param {goog.Uri} url The URL being requested.\n */\nWebChannelDebug.prototype.browserOfflineResponse = function(url) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'BROWSER_OFFLINE: ' + url;\n });\n};\n\n\n/**\n * Logs an XmlHttp request..\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {?string} postData The data posted in the request.\n */\nWebChannelDebug.prototype.xmlHttpChannelRequest = function(\n verb, uri, id, attempt, postData) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP REQ (' + id + ') [attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + self.maybeRedactPostData_(postData);\n });\n};\n\n\n/**\n * Logs the meta data received from an XmlHttp request.\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {goog.net.XmlHttp.ReadyState} readyState The ready state.\n * @param {number} statusCode The HTTP status code.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseMetaData = function(\n verb, uri, id, attempt, readyState, statusCode) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'XMLHTTP RESP (' + id + ') [ attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + readyState + ' ' + statusCode;\n });\n};\n\n\n/**\n * Logs the response data received from an XmlHttp request.\n * @param {string|number|undefined} id The request id.\n * @param {?string} responseText The response text.\n * @param {?string=} opt_desc Optional request description.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseText = function(\n id, responseText, opt_desc) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP TEXT (' + id + '): ' + self.redactResponse_(responseText) +\n (opt_desc ? ' ' + opt_desc : '');\n });\n};\n\n\n/**\n * Logs a request timeout.\n * @param {goog.Uri} uri The uri that timed out.\n */\nWebChannelDebug.prototype.timeoutResponse = function(uri) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'TIMEOUT: ' + uri;\n });\n};\n\n\n/**\n * Logs a debug message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.debug = function(text) {\n 'use strict';\n goog.log.fine(this.logger_, text);\n};\n\n\n/**\n * Logs an exception\n * @param {Error} e The error or error event.\n * @param {goog.log.Loggable=} opt_msg The optional message,\n * defaults to 'Exception'.\n */\nWebChannelDebug.prototype.dumpException = function(e, opt_msg) {\n 'use strict';\n goog.log.error(this.logger_, opt_msg || 'Exception', e);\n};\n\n\n/**\n * Logs an info message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.info = function(text) {\n 'use strict';\n goog.log.info(this.logger_, text);\n};\n\n\n/**\n * Logs a warning message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.warning = function(text) {\n 'use strict';\n goog.log.warning(this.logger_, text);\n};\n\n\n/**\n * Logs a severe message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.severe = function(text) {\n 'use strict';\n goog.log.error(this.logger_, text);\n};\n\n\n/**\n * Removes potentially private data from a response so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} responseText A JSON response to clean.\n * @return {?string} The cleaned response.\n * @private\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\nWebChannelDebug.prototype.redactResponse_ = function(responseText) {\n 'use strict';\n if (!this.redactEnabled_) {\n return responseText;\n }\n\n if (!responseText) {\n return null;\n }\n\n try {\n var responseArray = JSON.parse(responseText);\n if (responseArray) {\n for (var i = 0; i < responseArray.length; i++) {\n if (Array.isArray(responseArray[i])) {\n this.maybeRedactArray_(responseArray[i]);\n }\n }\n }\n\n return goog.json.serialize(responseArray);\n } catch (e) {\n this.debug('Exception parsing expected JS array - probably was not JS');\n return responseText;\n }\n};\n\n\n/**\n * Removes data from a response array that may be sensitive.\n * @param {!Array<?>} array The array to clean.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactArray_ = function(array) {\n 'use strict';\n if (array.length < 2) {\n return;\n }\n var dataPart = array[1];\n if (!Array.isArray(dataPart)) {\n return;\n }\n if (dataPart.length < 1) {\n return;\n }\n\n var type = dataPart[0];\n if (type != 'noop' && type != 'stop' && type != 'close') {\n // redact all fields in the array\n for (var i = 1; i < dataPart.length; i++) {\n dataPart[i] = '';\n }\n }\n};\n\n\n/**\n * Removes potentially private data from a request POST body so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} data The data string to clean.\n * @return {?string} The data string with sensitive data replaced by 'redacted'.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactPostData_ = function(data) {\n 'use strict';\n if (!this.redactEnabled_) {\n return data;\n }\n\n if (!data) {\n return null;\n }\n var out = '';\n var params = data.split('&');\n for (var i = 0; i < params.length; i++) {\n var param = params[i];\n var keyValue = param.split('=');\n if (keyValue.length > 1) {\n var key = keyValue[0];\n var value = keyValue[1];\n\n var keyParts = key.split('_');\n if (keyParts.length >= 2 && keyParts[1] == 'type') {\n out += key + '=' + value + '&';\n } else {\n out += key + '=' +\n 'redacted' +\n '&';\n }\n }\n }\n return out;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Static utilities for collecting stats associated with\n * ChannelRequest.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.requestStats');\ngoog.provide('goog.labs.net.webChannel.requestStats.Event');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachability');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachabilityEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.Stat');\ngoog.provide('goog.labs.net.webChannel.requestStats.StatEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.TimingEvent');\n\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventTarget');\n\n\ngoog.scope(function() {\n'use strict';\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\n\n/**\n * Events fired.\n * @const\n */\nrequestStats.Event = {};\n\n\n/**\n * Singleton event target for firing stat events\n * @type {?goog.events.EventTarget}\n * @private\n */\nrequestStats.eventTarget_ = null;\n\n/**\n * Singleton event target for firing stat events\n * @return {!goog.events.EventTarget}\n * @private\n */\nrequestStats.getStatEventTarget_ = function() {\n 'use strict';\n requestStats.eventTarget_ =\n requestStats.eventTarget_ || new goog.events.EventTarget();\n return requestStats.eventTarget_;\n};\n\n/**\n * The type of event that occurs every time some information about how reachable\n * the server is is discovered.\n */\nrequestStats.Event.SERVER_REACHABILITY_EVENT = 'serverreachability';\n\n\n/**\n * Types of events which reveal information about the reachability of the\n * server.\n * @enum {number}\n */\nrequestStats.ServerReachability = {\n REQUEST_MADE: 1,\n REQUEST_SUCCEEDED: 2,\n REQUEST_FAILED: 3,\n BACK_CHANNEL_ACTIVITY: 4 // any response data received\n};\n\n\n\n/**\n * Event class for SERVER_REACHABILITY_EVENT.\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.ServerReachabilityEvent = function(target, reachabilityType) {\n 'use strict';\n goog.events.Event.call(\n this, requestStats.Event.SERVER_REACHABILITY_EVENT, target);\n\n /**\n * @type {requestStats.ServerReachability}\n */\n this.reachabilityType = reachabilityType;\n};\ngoog.inherits(requestStats.ServerReachabilityEvent, goog.events.Event);\n\n\n/**\n * Notify the channel that a particular fine grained network event has occurred.\n * Should be considered package-private.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n */\nrequestStats.notifyServerReachabilityEvent = function(reachabilityType) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.ServerReachabilityEvent(target, reachabilityType));\n};\n\n\n/**\n * Stat Event that fires when things of interest happen that may be useful for\n * applications to know about for stats or debugging purposes.\n */\nrequestStats.Event.STAT_EVENT = 'statevent';\n\n\n/**\n * Enum that identifies events for statistics that are interesting to track.\n * @enum {number}\n */\nrequestStats.Stat = {\n /** Event indicating a new connection attempt. */\n CONNECT_ATTEMPT: 0,\n\n /** Event indicating a connection error due to a general network problem. */\n ERROR_NETWORK: 1,\n\n /**\n * Event indicating a connection error that isn't due to a general network\n * problem.\n */\n ERROR_OTHER: 2,\n\n /** Event indicating the start of test stage one. */\n TEST_STAGE_ONE_START: 3,\n\n /** Event indicating the start of test stage two. */\n TEST_STAGE_TWO_START: 4,\n\n /** Event indicating the first piece of test data was received. */\n TEST_STAGE_TWO_DATA_ONE: 5,\n\n /**\n * Event indicating that the second piece of test data was received and it was\n * received separately from the first.\n */\n TEST_STAGE_TWO_DATA_TWO: 6,\n\n /** Event indicating both pieces of test data were received simultaneously. */\n TEST_STAGE_TWO_DATA_BOTH: 7,\n\n /** Event indicating stage one of the test request failed. */\n TEST_STAGE_ONE_FAILED: 8,\n\n /** Event indicating stage two of the test request failed. */\n TEST_STAGE_TWO_FAILED: 9,\n\n /**\n * Event indicating that a buffering proxy is likely between the client and\n * the server.\n */\n PROXY: 10,\n\n /**\n * Event indicating that no buffering proxy is likely between the client and\n * the server.\n */\n NOPROXY: 11,\n\n /** Event indicating an unknown SID error. */\n REQUEST_UNKNOWN_SESSION_ID: 12,\n\n /** Event indicating a bad status code was received. */\n REQUEST_BAD_STATUS: 13,\n\n /** Event indicating incomplete data was received */\n REQUEST_INCOMPLETE_DATA: 14,\n\n /** Event indicating bad data was received */\n REQUEST_BAD_DATA: 15,\n\n /** Event indicating no data was received when data was expected. */\n REQUEST_NO_DATA: 16,\n\n /** Event indicating a request timeout. */\n REQUEST_TIMEOUT: 17,\n\n /**\n * Event indicating that the server never received our hanging GET and so it\n * is being retried.\n */\n BACKCHANNEL_MISSING: 18,\n\n /**\n * Event indicating that we have determined that our hanging GET is not\n * receiving data when it should be. Thus it is dead dead and will be retried.\n */\n BACKCHANNEL_DEAD: 19,\n\n /**\n * The browser declared itself offline during the lifetime of a request, or\n * was offline when a request was initially made.\n */\n BROWSER_OFFLINE: 20\n};\n\n\n\n/**\n * Event class for STAT_EVENT.\n *\n * @param {goog.events.EventTarget} eventTarget The stat event target for\n the channel.\n * @param {requestStats.Stat} stat The stat.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.StatEvent = function(eventTarget, stat) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.STAT_EVENT, eventTarget);\n\n /**\n * The stat\n * @type {requestStats.Stat}\n */\n this.stat = stat;\n};\ngoog.inherits(requestStats.StatEvent, goog.events.Event);\n\n\n/**\n * Returns the singleton event target for stat events.\n * @return {!goog.events.EventTarget} The event target for stat events.\n */\nrequestStats.getStatEventTarget = function() {\n 'use strict';\n return requestStats.getStatEventTarget_();\n};\n\n\n/**\n * Helper function to call the stat event callback.\n * @param {requestStats.Stat} stat The stat.\n */\nrequestStats.notifyStatEvent = function(stat) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(new requestStats.StatEvent(target, stat));\n};\n\n\n/**\n * An event that fires when POST requests complete successfully, indicating\n * the size of the POST and the round trip time.\n */\nrequestStats.Event.TIMING_EVENT = 'timingevent';\n\n\n\n/**\n * Event class for requestStats.Event.TIMING_EVENT\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {number} size The number of characters in the POST data.\n * @param {number} rtt The total round trip time from POST to response in MS.\n * @param {number} retries The number of times the POST had to be retried.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.TimingEvent = function(target, size, rtt, retries) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.TIMING_EVENT, target);\n\n /**\n * @type {number}\n */\n this.size = size;\n\n /**\n * @type {number}\n */\n this.rtt = rtt;\n\n /**\n * @type {number}\n */\n this.retries = retries;\n};\ngoog.inherits(requestStats.TimingEvent, goog.events.Event);\n\n\n/**\n * Helper function to notify listeners about POST request performance.\n *\n * @param {number} size Number of characters in the POST data.\n * @param {number} rtt The amount of time from POST start to response.\n * @param {number} retries The number of times the POST had to be retried.\n */\nrequestStats.notifyTimingEvent = function(size, rtt, retries) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.TimingEvent(target, size, rtt, retries));\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * starts processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} startHook The function for the start hook.\n */\nrequestStats.setStartThreadExecutionHook = function(startHook) {\n 'use strict';\n requestStats.startExecutionHook_ = startHook;\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * stops processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} endHook The function for the end hook.\n */\nrequestStats.setEndThreadExecutionHook = function(endHook) {\n 'use strict';\n requestStats.endExecutionHook_ = endHook;\n};\n\n\n/**\n * Application provided execution hook for the start hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.startExecutionHook_ = function() {};\n\n\n/**\n * Application provided execution hook for the end hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.endExecutionHook_ = function() {};\n\n\n/**\n * Helper function to call the start hook\n */\nrequestStats.onStartExecution = function() {\n 'use strict';\n requestStats.startExecutionHook_();\n};\n\n\n/**\n * Helper function to call the end hook\n */\nrequestStats.onEndExecution = function() {\n 'use strict';\n requestStats.endExecutionHook_();\n};\n\n\n/**\n * Wrapper around SafeTimeout which calls the start and end execution hooks\n * with a try...finally block.\n * @param {Function} fn The callback function.\n * @param {number} ms The time in MS for the timer.\n * @return {number} The ID of the timer.\n */\nrequestStats.setTimeout = function(fn, ms) {\n 'use strict';\n if (typeof fn !== 'function') {\n throw new Error('Fn must not be null and must be a function');\n }\n return goog.global.setTimeout(function() {\n 'use strict';\n requestStats.onStartExecution();\n try {\n fn();\n } finally {\n requestStats.onEndExecution();\n }\n }, ms);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview 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 'use strict';\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 The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\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","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface for a factory for creating XMLHttpRequest objects\n * and metadata about them.\n */\n\ngoog.provide('goog.net.XmlHttpFactory');\n\n/** @suppress {extraRequire} Typedef. */\ngoog.require('goog.net.XhrLike');\n\n\n\n/**\n * Abstract base class for an XmlHttpRequest factory.\n * @constructor\n */\ngoog.net.XmlHttpFactory = function() {};\n\n\n/**\n * Cache of options - we only actually call internalGetOptions once.\n * @type {?Object}\n * @private\n */\ngoog.net.XmlHttpFactory.prototype.cachedOptions_ = null;\n\n\n/**\n * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.\n */\ngoog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;\n\n\n/**\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n */\ngoog.net.XmlHttpFactory.prototype.getOptions = function() {\n 'use strict';\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","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The API spec for the WebChannel messaging library.\n *\n * Similar to HTML5 WebSocket, WebChannel offers an abstraction for\n * point-to-point socket-like communication between a browser client and\n * a remote origin.\n *\n * WebChannels are created via <code>WebChannel</code>. Multiple WebChannels\n * may be multiplexed over the same WebChannelTransport, which encapsulates\n * the underlying physical connectivity over standard wire protocols\n * such as HTTP.\n *\n * A WebChannel in turn represents a logical communication channel between\n * the client and server endpoint. A WebChannel remains open for as long\n * as the client or server endpoint allows.\n *\n * Messages are delivered in-order and reliably over the same WebChannel,\n * and the choice of the underlying wire protocols is completely transparent\n * to the API users.\n *\n * Note that we have no immediate plan to move this API out of labs. While\n * the implementation is production ready, the API is subject to change.\n */\n\ngoog.provide('goog.net.WebChannel');\ngoog.provide('goog.net.WebChannel.Options');\n\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * A WebChannel represents a logical bi-directional channel over which the\n * client communicates with a remote server that holds the other endpoint\n * of the channel. A WebChannel is always created in the context of a shared\n * {@link WebChannelTransport} instance. It is up to the underlying client-side\n * and server-side implementations to decide how or when multiplexing is\n * to be enabled.\n *\n * @interface\n * @extends {goog.events.Listenable}\n */\ngoog.net.WebChannel = function() {};\n\n\n\n/**\n * This interface defines a pluggable API to allow WebChannel runtime to support\n * customized algorithms in order to recover from transient failures such as\n * those failures caused by network or proxies (intermediaries).\n *\n * The algorithm may also choose to fail-fast, e.g. switch the client to some\n * offline mode.\n *\n * Extra measurements and logging could also be implemented in the custom\n * module, which has the full knowledge of all the state transitions\n * (due to failures).\n *\n * A default algorithm will be provided by the webchannel library itself. Custom\n * algorithms are expected to be tailored to specific client platforms or\n * networking environments, e.g. mobile, cellular network.\n *\n * @interface\n */\ngoog.net.WebChannel.FailureRecovery = function() {};\n\n\n/**\n * Configuration spec for newly created WebChannel instances.\n *\n * WebChannels are configured in the context of the containing\n * {@link WebChannelTransport}. The configuration parameters are specified\n * when a new instance of WebChannel is created via {@link WebChannelTransport}.\n * @record\n */\ngoog.net.WebChannel.Options = function() {};\n\n/**\n * Transport-metadata support.\n *\n * Custom HTTP headers to be added to every message sent to the server. This\n * object is mutable, and custom headers may be changed, removed, or added\n * during the runtime after a channel has been opened.\n *\n * Custom headers may trigger CORS preflight. See other related options.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageHeaders;\n\n/**\n * Transport-metadata support.\n *\n * Similar to messageHeaders, but any custom HTTP headers will be sent only once\n * when the channel is opened as part of the handshake request. Typical usage is\n * to send an auth header to the server, which only checks the auth header at\n * the time during the handshake when the channel is opened.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.initMessageHeaders;\n\n/**\n * Sent as initMessageHeaders via X-WebChannel-Content-Type,\n * to inform the server the MIME type of WebChannel messages.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageContentType;\n\n/**\n * Transport-metadata support.\n *\n * Custom url query parameters to be added to every message sent to the server.\n * This object is mutable, and custom parameters may be changed, removed or\n * added during the runtime after a channel has been opened.\n *\n * TODO: initMessageUrlParams\n * TODO: closeMessageUrlParams (custom url query params to be added to the\n * channel-close message. Custom headers are not supported due to the use of\n * SendBeacon)\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageUrlParams;\n\n/**\n * Whether a special header should be added to\n * each message so that the server can dispatch webchannel messages without\n * knowing the URL path prefix. Defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProtocolHeaderRequired;\n\n/**\n * The maximum number of in-flight HTTP requests allowed\n * when SPDY is enabled. Currently we only detect SPDY in Chrome.\n * This parameter defaults to 10. When SPDY is not enabled, this parameter\n * will have no effect.\n * @type {number|undefined}\n */\ngoog.net.WebChannel.Options.prototype.concurrentRequestLimit;\n\n/**\n * Setting this to true to allow the use of sub-domains\n * (as configured by the server) to send XHRs with the CORS withCredentials\n * bit set to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.supportsCrossDomainXhr;\n\n/**\n * Whether to bypass v8 encoding of client-sent messages.\n * This defaults to false now due to legacy servers. New applications should\n * always configure this option to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.sendRawJson;\n\n/**\n * The URL parameter name that contains the session id (for sticky routing of\n * HTTP requests). When this param is specified, a server that supports this\n * option will respond with an opaque session id as part of the initial\n * handshake (via the X-HTTP-Session-Id header); and all the subsequent requests\n * will contain the httpSessionIdParam. This option will take precedence over\n * any duplicated parameter specified with messageUrlParams, whose value will be\n * ignored.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpSessionIdParam;\n\n/**\n * The URL parameter name to allow custom HTTP\n * headers to be overwritten as a URL param to bypass CORS preflight.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpHeadersOverwriteParam;\n\n/**\n * Whether to encode Options.initMessageHeaders in the HTTP request body.\n * This option defaults to false. If true, Options.httpHeadersOverwriteParam\n * will be ignored.\n *\n * This option should not be set if Options.fastHandshake is set (which\n * uses GET for handshake).\n *\n * Web-only feature.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.encodeInitMessageHeaders;\n\n/**\n * Whether to force long-polling from client to server.\n * This defaults to false. Long-polling may be necessary when a (MITM) proxy\n * is buffering data sent by the server.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.forceLongPolling;\n\n/**\n * Whether to enable automatic detection of buffering proxies. In the presence\n * of any buffering proxy, webchannel will use long-polling to send messages\n * from the server to the client. This option defaults to false.\n * Currently when fastHandshake is enabled, this option will be ignored.\n * Compared to \"forceLongPolling\", this option may introduce up to 2-RTT\n * extra latency for delivering messages generated immediately after the\n * handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.detectBufferingProxy;\n\n/**\n * This option informs the server the desired maximum timeout interval (in\n * Milliseconds) to complete a long-polling GET response, e.g. to accommodate\n * the timeout enforced by a proxy. The WebChannel server may adjust the\n * specified timeout or may ignore this client-configured timeout.\n * @type {number|undefined}\n */\ngoog.net.WebChannel.Options.prototype.longPollingTimeout;\n\n/**\n * Enable true 0-RTT message delivery, including\n * leveraging QUIC 0-RTT (which requires GET to be used). This option\n * defaults to false. Note it is allowed to send messages before Open event is\n * received, after a channel has been opened. In order to enable 0-RTT,\n * messages will be encoded as part of URL and therefore there needs be a size\n * limit for those initial messages that are sent immediately as part of the\n * GET handshake request. With sendRawJson=true, this limit is currently set\n * to 4K chars and data beyond this limit will be buffered till the handshake\n * (1-RTT) finishes. With sendRawJson=false, it's up to the application\n * to limit the amount of data that is sent as part of the handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.fastHandshake;\n\n/**\n * Enable the blocking RPC semantics for the handshake:\n * 1) the completion of handshake is blocked by the server-side application\n * logic for handling the handshake (HTTP) request; 2) the client application\n * will inspect the handshake (HTTP) response headers as generated\n * by the server application (v.s. by only the webchannel runtime). This option\n * defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.blockingHandshake;\n\n/**\n * Whether to disable logging redact. By default, redact is\n * enabled to remove any message payload or user-provided info\n * from closure logs.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.disableRedact;\n\n/**\n * Inform the server about the client profile to enable\n * customized configs that are optimized for certain clients or environments.\n * Currently this information is sent via X-WebChannel-Client-Profile header.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProfile;\n\n/**\n * The internal channel parameter name to allow\n * experimental channel configurations. Supported options include fastfail,\n * baseRetryDelayMs, retryDelaySeedMs, forwardChannelMaxRetries and\n * forwardChannelRequestTimeoutMs. Note that these options are subject to\n * change.\n * @type {!Object<string, boolean|number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.internalChannelParams;\n\n/**\n * Allows the caller to override the factory used to create\n * XMLHttpRequest objects. This is introduced to disable CORS on firefox OS.\n * @type {!goog.net.XmlHttpFactory|undefined}\n */\ngoog.net.WebChannel.Options.prototype.xmlHttpFactory;\n\n/**\n * Client-side thresholds that decide when to refresh\n * an underlying HTTP request, to limit memory consumption due to XHR buffering\n * or compression context. The client-side thresholds should be significantly\n * smaller than the server-side thresholds. This allows the client to eliminate\n * any latency introduced by request refreshing, i.e. an RTT window during which\n * messages may be buffered on the server-side. Supported params include\n * totalBytesReceived, totalDurationMs.\n * @type {!Object<string, number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.requestRefreshThresholds;\n\n/**\n * This is an experimental feature to use WHATWG Fetch/streams (when supported).\n * If a custom 'xmlHttpFactory' is speficied, this option will not be effective.\n * This option defaults to false now and will eventually be turned on by\n * default.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.useFetchStreams;\n\n/**\n * Opt-in to enable Chrome origin trials from the WebChannel client. See\n * https://github.com/GoogleChrome/OriginTrials\n *\n * Origin trial history:\n * - fetch upload (11/2020 - 07/2021)\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * Participating in the origin trials will help Chrome to release new Web\n * platform features sooner, which will in turn help improve WebChannel\n * performance.\n *\n * Origin trials are not expected to interfere with WebChannel wire messages\n * and should not introduce any noticeable overhead.\n *\n * This is enabled by default with any on-going origin-trial.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.enableOriginTrials;\n\n\n/**\n * Types that are allowed as message data.\n *\n * Note that JS objects (sent by the client) can only have string encoded\n * values due to the limitation of the current wire protocol.\n *\n * Unicode strings (sent by the server) may or may not need be escaped, as\n * decided by the server.\n *\n * @typedef {(!ArrayBuffer|!Blob|!Object<string, !Object|string>|!Array|string)}\n */\ngoog.net.WebChannel.MessageData;\n\n\n/**\n * Open the WebChannel against the URI specified in the constructor.\n */\ngoog.net.WebChannel.prototype.open = goog.abstractMethod;\n\n\n/**\n * Close the WebChannel.\n *\n * This is a full close (shutdown) with no guarantee of FIFO delivery in respect\n * to any in-flight messages sent to the server.\n *\n * If you need such a guarantee, see the Half the halfClose() method.\n */\ngoog.net.WebChannel.prototype.close = goog.abstractMethod;\n\n\n/**\n * Half-close the WebChannel.\n *\n * Half-close semantics:\n * 1. delivered as a regular message in FIFO programming order\n * 2. the server is expected to return a half-close too (with or without\n * application involved), which will trigger a full close (shutdown)\n * on the client side\n * 3. for now, the half-close event defined for server-initiated\n * half-close is not exposed to the client application\n * 4. a client-side half-close may be triggered internally when the client\n * receives a half-close from the server; and the client is expected to\n * do a full close after the half-close is acked and delivered\n * on the server-side.\n * 5. Full close is always a forced one. See the close() method.\n *\n * New messages sent after halfClose() will be dropped.\n *\n * NOTE: This is not yet implemented, and will throw an exception if called.\n */\ngoog.net.WebChannel.prototype.halfClose = goog.abstractMethod;\n\n\n/**\n * Sends a message to the server that maintains the other endpoint of\n * the WebChannel.\n *\n * O-RTT behavior:\n * 1. messages sent before open() is called will always be delivered as\n * part of the handshake, i.e. with 0-RTT\n * 2. messages sent after open() is called but before the OPEN event\n * is received will be delivered as part of the handshake if\n * send() is called from the same execution context as open().\n * 3. otherwise, those messages will be buffered till the handshake\n * is completed (which will fire the OPEN event).\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n */\ngoog.net.WebChannel.prototype.send = goog.abstractMethod;\n\n\n/**\n * Common events fired by WebChannels.\n * @enum {string}\n */\ngoog.net.WebChannel.EventType = {\n /** Dispatched when the channel is opened. */\n OPEN: goog.events.getUniqueId('open'),\n\n /** Dispatched when the channel is closed. */\n CLOSE: goog.events.getUniqueId('close'),\n\n /**\n * Dispatched when the channel is aborted due to errors.\n *\n * For backward compatibility reasons, a CLOSE event will also be\n * dispatched, following the ERROR event, which indicates that the channel\n * has been completely shutdown .\n */\n ERROR: goog.events.getUniqueId('error'),\n\n /** Dispatched when the channel has received a new message. */\n MESSAGE: goog.events.getUniqueId('message')\n};\n\n\n\n/**\n * The event interface for the MESSAGE event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.MessageEvent = function() {\n 'use strict';\n goog.net.WebChannel.MessageEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.MESSAGE);\n};\ngoog.inherits(goog.net.WebChannel.MessageEvent, goog.events.Event);\n\n\n/**\n * The content of the message received from the server.\n *\n * @type {!goog.net.WebChannel.MessageData}\n */\ngoog.net.WebChannel.MessageEvent.prototype.data;\n\n\n/**\n * The metadata key when the MESSAGE event represents a metadata message.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.metadataKey;\n\n\n/**\n * Metadata as HTTP status code. Typically sent before the channel is\n * half-closed by the server.\n *\n * @type {number|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.statusCode;\n\n\n/**\n * Metadata as HTTP headers. Typically sent before the channel is\n * half-closed by the server.\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.headers;\n\n\n/**\n * WebChannel level error conditions.\n *\n * Summary of error debugging and reporting in WebChannel:\n *\n * Network Error\n * 1. By default the webchannel library will set the error status to\n * NETWORK_ERROR when a channel has to be aborted or closed. NETWORK_ERROR\n * may be recovered by the application by retrying and opening a new channel.\n * 2. There may be lost messages (not acked by the server) when a channel is\n * aborted. Currently we don't have a public API to retrieve messages that\n * are waiting to be acked on the client side. File a bug if you think it\n * is useful to expose such an API.\n * 3. Details of why a channel fails are available via closure debug logs,\n * and stats events (see webchannel/requeststats.js). Those are internal\n * stats and are subject to change. File a bug if you think it's useful to\n * version and expose such stats as part of the WebChannel API.\n *\n * Server Error\n * 1. SERVER_ERROR is intended to indicate a non-recoverable condition, e.g.\n * when auth fails.\n * 2. We don't currently generate any such errors, because most of the time\n * it's the responsibility of upper-layer frameworks or the application\n * itself to indicate to the client why a webchannel has been failed\n * by the server.\n * 3. When a channel is failed by the server explicitly, we still signal\n * NETWORK_ERROR to the client. Explicit server failure may happen when the\n * server does a fail-over, or becomes overloaded, or conducts a forced\n * shutdown etc.\n * 4. We use some heuristic to decide if the network (aka cloud) is down\n * v.s. the actual server is down.\n *\n * RuntimeProperties.getLastStatusCode is a useful state that we expose to\n * the client to indicate the HTTP response status code of the last HTTP\n * request initiated by the WebChannel client library, for debugging\n * purposes only.\n *\n * See WebChannel.Options.backChannelFailureRecovery and\n * WebChannel.FailureRecovery to install a custom failure-recovery algorithm.\n *\n * @enum {number}\n */\ngoog.net.WebChannel.ErrorStatus = {\n /** No error has occurred. */\n OK: 0,\n\n /** Communication to the server has failed. */\n NETWORK_ERROR: 1,\n\n /** The server fails to accept or process the WebChannel. */\n SERVER_ERROR: 2\n};\n\n\n\n/**\n * The event interface for the ERROR event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.ErrorEvent = function() {\n 'use strict';\n goog.net.WebChannel.ErrorEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.ERROR);\n};\ngoog.inherits(goog.net.WebChannel.ErrorEvent, goog.events.Event);\n\n\n/**\n * The error status.\n *\n * @type {!goog.net.WebChannel.ErrorStatus}\n */\ngoog.net.WebChannel.ErrorEvent.prototype.status;\n\n\n/**\n * @return {!goog.net.WebChannel.RuntimeProperties} The runtime properties\n * of the WebChannel instance.\n */\ngoog.net.WebChannel.prototype.getRuntimeProperties = goog.abstractMethod;\n\n\n\n/**\n * The runtime properties of the WebChannel instance.\n *\n * This class is defined for debugging and monitoring purposes, as well as for\n * runtime functions that the application may choose to manage by itself.\n *\n * @interface\n */\ngoog.net.WebChannel.RuntimeProperties = function() {};\n\n\n/**\n * @return {number} The effective limit for the number of concurrent HTTP\n * requests that are allowed to be made for sending messages from the client\n * to the server. When SPDY is not enabled, this limit will be one.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getConcurrentRequestLimit =\n goog.abstractMethod;\n\n\n/**\n * For applications that need support multiple channels (e.g. from\n * different tabs) to the same origin, use this method to decide if SPDY is\n * enabled and therefore it is safe to open multiple channels.\n *\n * If SPDY is disabled, the application may choose to limit the number of active\n * channels to one or use other means such as sub-domains to work around\n * the browser connection limit.\n *\n * @return {boolean} Whether SPDY is enabled for the origin against which\n * the channel is created.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.isSpdyEnabled =\n goog.abstractMethod;\n\n\n/**\n * @return {number} The number of requests (for sending messages to the server)\n * that are pending. If this number is approaching the value of\n * getConcurrentRequestLimit(), client-to-server message delivery may experience\n * a higher latency.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getPendingRequestCount =\n goog.abstractMethod;\n\n\n/**\n * For applications to query the current HTTP session id, sent by the server\n * during the initial handshake.\n *\n * @return {?string} the HTTP session id or null if no HTTP session is in use.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getHttpSessionId =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method generates an in-band commit request to the server, which will\n * ack the commit request as soon as all messages sent prior to this commit\n * request have been committed by the application.\n *\n * Committing a message has a stronger semantics than delivering a message\n * to the application. Detail spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Timeout or cancellation is not supported and the application is expected to\n * abort the channel if the commit-ack fails to arrive in time.\n *\n * ===\n *\n * This is currently implemented only in the client layer and the commit\n * callback will be invoked after all the pending client-sent messages have been\n * delivered by the server-side webchannel endpoint. This semantics is\n * different and weaker than what's required for end-to-end ack which requires\n * the server application to ack the in-order delivery of messages that are sent\n * before the commit request is issued.\n *\n * Commit should only be called after the channel open event is received.\n * Duplicated commits are allowed and only the last callback is guaranteed.\n * Commit called after the channel has been closed will be ignored.\n *\n * @param {function()} callback The callback will be invoked once an\n * ack has been received for the current commit or any newly issued commit.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.commit = goog.abstractMethod;\n\n\n/**\n * This method may be used by the application to recover from a peer failure\n * or to enable sender-initiated flow-control.\n *\n * Detail spec: https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Note that the caller should NOT modify the list of returned messages.\n *\n * @return {!Array<!goog.net.WebChannel.MessageData>} The list of messages that\n * have not received commit-ack from the server; or if no commit has been\n * issued, the list of messages that have not been delivered to the server\n * application.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getNonAckedMessages =\n goog.abstractMethod;\n\n\n/**\n * A low water-mark message count to notify the application when the\n * flow-control condition is cleared, that is, when the application is\n * able to send more messages.\n *\n * We expect the application to configure a high water-mark message count,\n * which is checked via getNonAckedMessageCount(). When the high water-mark\n * is exceeded, the application should install a callback via this method\n * to be notified when to start to send new messages.\n *\n * This is not yet implemented.\n *\n * @param {number} count The low water-mark count. It is an error to pass\n * a non-positive value.\n * @param {function()} callback The call back to notify the application\n * when NonAckedMessageCount is below the specified low water-mark count.\n * Any previously registered callback is cleared. This new callback will\n * be cleared once it has been fired, or when the channel is closed or aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method registers a callback to handle the commit request sent\n * by the server. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {function(!Object)} callback The callback will take an opaque\n * commitId which needs be passed back to the server when an ack-commit\n * response is generated by the client application, via ackCommit().\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.onCommit = goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method is used by the application to generate an ack-commit response\n * for the given commitId. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {!Object} commitId The commitId which denotes the commit request\n * from the server that needs be ack'ed.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.ackCommit = goog.abstractMethod;\n\n\n/**\n * Transport-metadata support.\n *\n * Responses from the channel-close (abort) message are not available.\n *\n * In future when client-side half-close is supported, its response headers\n * will be available via this API too.\n * @return {!Object<string, string>|undefined} The response headers received\n * with the non-200 HTTP status code that causes the channel to be aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastResponseHeaders =\n goog.abstractMethod;\n\n/**\n * Transport-metadata support.\n *\n * TODO: getInitStatusCode (handshake)\n * TODO: getInitResponseHeaders (handshake)\n *\n * Note that response headers from client-initiated close (abort) are not\n * available.\n *\n * In future when client-initiated half-close is supported, its response status\n * will be available via this API.\n *\n * @return {number} The non-200 HTTP status code received that causes the\n * channel to be aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastStatusCode =\n goog.abstractMethod;\n\n\n/**\n * Enum to indicate the current recovery state.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.State = {\n /** Initial state. */\n INIT: 'init',\n\n /** Once a failure has been detected. */\n FAILED: 'failed',\n\n /**\n * Once a recovery operation has been issued, e.g. a new request to resume\n * communication.\n */\n RECOVERING: 'recovering',\n\n /** The channel has been closed. */\n CLOSED: 'closed'\n};\n\n\n/**\n * Enum to indicate different failure conditions as detected by the webchannel\n * runtime.\n *\n * This enum is to be used only between the runtime and FailureRecovery module,\n * and new states are expected to be introduced in future.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.FailureCondition = {\n /**\n * The HTTP response returned a non-successful http status code.\n */\n HTTP_ERROR: 'http_error',\n\n /**\n * The request was aborted.\n */\n ABORT: 'abort',\n\n /**\n * The request timed out.\n */\n TIMEOUT: 'timeout',\n\n /**\n * Exception was thrown while processing the request/response.\n */\n EXCEPTION: 'exception'\n};\n\n\n/**\n * @return {!goog.net.WebChannel.FailureRecovery.State} the current state,\n * mainly for debugging use.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.getState = goog.abstractMethod;\n\n\n/**\n * This method is for WebChannel runtime to set the current failure condition\n * and to provide a callback for the algorithm to signal to the runtime\n * when it is time to issue a recovery operation, e.g. a new request to the\n * server.\n *\n * Supported transitions include:\n * INIT->FAILED\n * FAILED->FAILED (re-entry ok)\n * RECOVERY->FAILED.\n *\n * Ignored if state == CLOSED.\n *\n * Advanced implementations are expected to track all the state transitions\n * and their timestamps for monitoring purposes.\n *\n * @param {!goog.net.WebChannel.FailureRecovery.FailureCondition} failure The\n * new failure condition generated by the WebChannel runtime.\n * @param {!Function} operation The callback function to the WebChannel\n * runtime to issue a recovery operation, e.g. a new request. E.g. the default\n * recovery algorithm will issue timeout-based recovery operations.\n * Post-condition for the callback: state transition to RECOVERING.\n *\n * @return {!goog.net.WebChannel.FailureRecovery.State} The updated state\n * as decided by the failure recovery module. Upon a recoverable failure event,\n * the state is transitioned to RECOVERING; or the state is transitioned to\n * FAILED which indicates a fail-fast decision for the runtime to execute.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.setFailure = goog.abstractMethod;\n\n\n/**\n * The Webchannel runtime needs call this method when webchannel is closed or\n * aborted.\n *\n * Once the instance is closed, any access to the instance will be a no-op.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.close = goog.abstractMethod;\n\n\n/**\n * A request header to indicate to the server the messaging protocol\n * each HTTP message is speaking.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL = 'X-Client-Protocol';\n\n\n/**\n * The value for x-client-protocol when the messaging protocol is WebChannel.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL = 'webchannel';\n\n\n/**\n * A response header for the server to signal the wire-protocol that\n * the browser establishes with the server (or proxy), e.g. \"spdy\" (aka http/2)\n * \"quic\". This information avoids the need to use private APIs to decide if\n * HTTP requests are multiplexed etc.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL = 'X-Client-Wire-Protocol';\n\n\n/**\n * A response header for the server to send back the HTTP session id as part of\n * the initial handshake. The value of the HTTP session id is opaque to the\n * WebChannel protocol.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_SESSION_ID = 'X-HTTP-Session-Id';\n\n\n/**\n * A response header for the server to send back any initial response data as a\n * header to avoid any possible buffering by an intermediary, which may\n * be undesired during the handshake.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_INITIAL_RESPONSE = 'X-HTTP-Initial-Response';\n\n\n/**\n * A request header for specifying the content-type of WebChannel messages,\n * e.g. application-defined JSON encoding styles. Currently this header\n * is sent by the client via initMessageHeaders when the channel is opened.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE = 'X-WebChannel-Content-Type';\n\n\n/**\n * A request header for specifying the client profile in order to apply\n * customized config params on the server side, e.g. timeouts.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE = 'X-WebChannel-Client-Profile';\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Low level handling of XMLHttpRequest.\n */\n\ngoog.provide('goog.net.DefaultXmlHttpFactory');\ngoog.provide('goog.net.XmlHttp');\ngoog.provide('goog.net.XmlHttp.OptionType');\ngoog.provide('goog.net.XmlHttp.ReadyState');\ngoog.provide('goog.net.XmlHttpDefines');\n\ngoog.require('goog.asserts');\ngoog.require('goog.net.WrapperXmlHttpFactory');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.requireType('goog.net.XhrLike');\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 'use strict';\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 'use strict';\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 no-op function 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 'use strict';\n goog.net.XmlHttp.setGlobalFactory(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 'use strict';\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 'use strict';\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 'use strict';\n const 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 'use strict';\n const progId = this.getProgId_();\n const 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 'use strict';\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 const ACTIVE_X_IDENTS = [\n 'MSXML2.XMLHTTP.6.0',\n 'MSXML2.XMLHTTP.3.0',\n 'MSXML2.XMLHTTP',\n 'Microsoft.XMLHTTP',\n ];\n for (let i = 0; i < ACTIVE_X_IDENTS.length; i++) {\n const 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 The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the ChannelRequest class. The request\n * object encapsulates the logic for making a single request, either for the\n * forward channel, back channel, or test channel, to the server. It contains\n * the logic for the two types of transports we use:\n * XMLHTTP and Image request. It provides timeout detection. More transports\n * to be added in future, such as Fetch, WebSocket.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.ChannelRequest');\n\ngoog.require('goog.Timer');\ngoog.require('goog.asserts');\ngoog.require('goog.async.Throttle');\ngoog.require('goog.dispose');\ngoog.require('goog.events.EventHandler');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.labs.net.webChannel.Wire.QueuedMap');\ngoog.requireType('goog.net.XhrIo');\n\n\n\n/**\n * A new ChannelRequest is created for each request to the server.\n *\n * @param {goog.labs.net.webChannel.Channel} channel\n * The channel that owns this request.\n * @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A\n * WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.ChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n /**\n * The channel object that owns the request.\n * @private {goog.labs.net.webChannel.Channel}\n */\n this.channel_ = channel;\n\n /**\n * The channel debug to use for logging\n * @private {goog.labs.net.webChannel.WebChannelDebug}\n */\n this.channelDebug_ = channelDebug;\n\n /**\n * The Session ID for the channel.\n * @private {string|undefined}\n */\n this.sid_ = opt_sessionId;\n\n /**\n * The RID (request ID) for the request.\n * @private {string|number|undefined}\n */\n this.rid_ = opt_requestId;\n\n /**\n * The attempt number of the current request.\n * @private {number}\n */\n this.retryId_ = opt_retryId || 1;\n\n /**\n * An object to keep track of the channel request event listeners.\n * @private {!goog.events.EventHandler<\n * !goog.labs.net.webChannel.ChannelRequest>}\n */\n this.eventHandler_ = new goog.events.EventHandler(this);\n\n /**\n * The timeout in ms before failing the request.\n * @private {number}\n */\n this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;\n\n /**\n * A timer for polling responseText in browsers that don't fire\n * onreadystatechange during incremental loading of responseText.\n * @private {goog.Timer}\n */\n this.pollingTimer_ =\n new goog.Timer(goog.labs.net.webChannel.environment.getPollingInterval());\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n\n /**\n * Whether the request was successful. This is only set to true after the\n * request successfully completes.\n * @private {boolean}\n */\n this.successful_ = false;\n\n\n /**\n * The TimerID of the timer used to detect if the request has timed-out.\n * @type {?number}\n * @private\n */\n this.watchDogTimerId_ = null;\n\n /**\n * The time in the future when the request will timeout.\n * @private {?number}\n */\n this.watchDogTimeoutTime_ = null;\n\n /**\n * The time the request started.\n * @private {?number}\n */\n this.requestStartTime_ = null;\n\n /**\n * The type of request (XMLHTTP, IMG)\n * @private {?number}\n */\n this.type_ = null;\n\n /**\n * The base Uri for the request. The includes all the parameters except the\n * one that indicates the retry number.\n * @private {?goog.Uri}\n */\n this.baseUri_ = null;\n\n /**\n * The request Uri that was actually used for the most recent request attempt.\n * @private {?goog.Uri}\n */\n this.requestUri_ = null;\n\n /**\n * The post data, if the request is a post.\n * @private {?string}\n */\n this.postData_ = null;\n\n /**\n * An array of pending messages that we have either received a non-successful\n * response for, or no response at all, and which therefore may or may not\n * have been received by the server.\n * @private {!Array<goog.labs.net.webChannel.Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n\n /**\n * The XhrLte request if the request is using XMLHTTP\n * @private {?goog.net.XhrIo}\n */\n this.xmlHttp_ = null;\n\n /**\n * The position of where the next unprocessed chunk starts in the response\n * text.\n * @private {number}\n */\n this.xmlHttpChunkStart_ = 0;\n\n /**\n * The verb (Get or Post) for the request.\n * @private {?string}\n */\n this.verb_ = null;\n\n /**\n * The last error if the request failed.\n * @private {?goog.labs.net.webChannel.ChannelRequest.Error}\n */\n this.lastError_ = null;\n\n /**\n * The response headers received along with the non-200 status.\n *\n * @private {!Object<string, string>|undefined}\n */\n this.errorResponseHeaders_ = undefined;\n\n /**\n * The last status code received.\n * @private {number}\n */\n this.lastStatusCode_ = -1;\n\n /**\n * Whether the request has been cancelled due to a call to cancel.\n * @private {boolean}\n */\n this.cancelled_ = false;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n * If set to zero no throttle is used.\n *\n * See WebChannelBase.prototype.readyStateChangeThrottleMs_\n *\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * The throttle for readystatechange events for the current request, or null\n * if there is none.\n * @private {?goog.async.Throttle}\n */\n this.readyStateChangeThrottle_ = null;\n\n /**\n * Whether to the result is expected to be encoded for chunking and thus\n * requires decoding.\n * @private {boolean}\n */\n this.decodeChunks_ = false;\n\n /**\n * Whether to decode x-http-initial-response.\n * @private {boolean}\n */\n this.decodeInitialResponse_ = false;\n\n /**\n * Whether x-http-initial-response has been decoded (dispatched).\n * @private {boolean}\n */\n this.initialResponseDecoded_ = false;\n\n /**\n * Whether the first byte of response body has arrived, for a successful\n * response.\n * @private {boolean}\n */\n this.firstByteReceived_ = false;\n\n /**\n * The current state of fetch responses if webchannel is using WHATWG\n * fetch/streams.\n * @private {!goog.labs.net.webChannel.FetchResponseState}\n */\n this.fetchResponseState_ = new goog.labs.net.webChannel.FetchResponseState();\n};\n\n/**\n * A collection of fetch/stream properties.\n * @struct\n * @constructor\n */\ngoog.labs.net.webChannel.FetchResponseState = function() {\n 'use strict';\n /**\n * The TextDecoder for decoding Uint8Array responses from fetch request.\n * @type {?goog.global.TextDecoder}\n */\n this.textDecoder = null;\n\n /**\n * The unconsumed response text from the fetch requests.\n * @type {string}\n */\n this.responseBuffer = '';\n\n /**\n * Whether or not the response body has arrived.\n * @type {boolean}\n */\n this.responseArrivedForFetch = false;\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst Channel = goog.labs.net.webChannel.Channel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst FetchResponseState = goog.labs.net.webChannel.FetchResponseState;\nconst requestStats = goog.labs.net.webChannel.requestStats;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst environment = goog.labs.net.webChannel.environment;\n\n/**\n * Default timeout in MS for a request. The server must return data within this\n * time limit for the request to not timeout.\n * @private {number}\n */\nChannelRequest.TIMEOUT_MS_ = 45 * 1000;\n\n\n/**\n * Enum for channel requests type\n * @enum {number}\n * @private\n */\nChannelRequest.Type_ = {\n /**\n * XMLHTTP requests.\n */\n XML_HTTP: 1,\n\n /**\n * IMG requests.\n */\n CLOSE_REQUEST: 2\n};\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nChannelRequest.Error = {\n /**\n * Errors due to a non-200 status code.\n */\n STATUS: 0,\n\n /**\n * Errors due to no data being returned.\n */\n NO_DATA: 1,\n\n /**\n * Errors due to a timeout.\n */\n TIMEOUT: 2,\n\n /**\n * Errors due to the server returning an unknown.\n */\n UNKNOWN_SESSION_ID: 3,\n\n /**\n * Errors due to bad data being received.\n */\n BAD_DATA: 4,\n\n /**\n * Errors due to the handler throwing an exception.\n */\n HANDLER_EXCEPTION: 5,\n\n /**\n * The browser declared itself offline during the request.\n */\n BROWSER_OFFLINE: 6\n};\n\n\n/**\n * Returns a useful error string for debugging based on the specified error\n * code.\n * @param {?ChannelRequest.Error} errorCode The error code.\n * @param {number} statusCode The HTTP status code.\n * @return {string} The error string for the given code combination.\n */\nChannelRequest.errorStringFromCode = function(errorCode, statusCode) {\n 'use strict';\n switch (errorCode) {\n case ChannelRequest.Error.STATUS:\n return 'Non-200 return code (' + statusCode + ')';\n case ChannelRequest.Error.NO_DATA:\n return 'XMLHTTP failure (no data)';\n case ChannelRequest.Error.TIMEOUT:\n return 'HttpConnection timeout';\n default:\n return 'Unknown error';\n }\n};\n\n\n/**\n * Sentinel value used to indicate an invalid chunk in a multi-chunk response.\n * @private {!Object}\n */\nChannelRequest.INVALID_CHUNK_ = {};\n\n\n/**\n * Sentinel value used to indicate an incomplete chunk in a multi-chunk\n * response.\n * @private {!Object}\n */\nChannelRequest.INCOMPLETE_CHUNK_ = {};\n\n\n/**\n * Returns whether XHR streaming is supported on this browser.\n *\n * @return {boolean} Whether XHR streaming is supported.\n * @see http://code.google.com/p/closure-library/issues/detail?id=346\n */\nChannelRequest.supportsXhrStreaming = function() {\n 'use strict';\n return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers.\n */\nChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Overrides the default HTTP method.\n *\n * @param {string} verb The HTTP method\n */\nChannelRequest.prototype.setVerb = function(verb) {\n 'use strict';\n this.verb_ = verb;\n};\n\n\n/**\n * Sets the timeout for a request\n *\n * @param {number} timeout The timeout in MS for when we fail the request.\n */\nChannelRequest.prototype.setTimeout = function(timeout) {\n 'use strict';\n this.timeout_ = timeout;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets the pending messages that this request is handling.\n *\n * @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} pendingMessages\n * The pending messages for this request.\n */\nChannelRequest.prototype.setPendingMessages = function(pendingMessages) {\n 'use strict';\n this.pendingMessages_ = pendingMessages;\n};\n\n\n/**\n * Gets the pending messages that this request is handling, in case of a retry.\n *\n * @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending\n * messages for this request.\n */\nChannelRequest.prototype.getPendingMessages = function() {\n 'use strict';\n return this.pendingMessages_;\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP POST to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {?string} postData The data for the post body.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n */\nChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = postData;\n this.decodeChunks_ = decodeChunks;\n this.sendXmlHttp_(null /* hostPrefix */);\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP GET to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n * @param {?string} hostPrefix The host prefix, if we might be using a\n * secondary domain. Note that it should also be in the URL, adding this\n * won't cause it to be added to the URL.\n */\nChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = null;\n this.decodeChunks_ = decodeChunks;\n\n this.sendXmlHttp_(hostPrefix);\n};\n\n\n/**\n * Sends a request via XMLHTTP according to the current state of the request\n * object.\n *\n * @param {?string} hostPrefix The host prefix, if we might be using a secondary\n * domain.\n * @private\n */\nChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {\n 'use strict';\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n\n // clone the base URI to create the request URI. The request uri has the\n // attempt number as a parameter which helps in debugging.\n this.requestUri_ = this.baseUri_.clone();\n this.requestUri_.setParameterValues('t', this.retryId_);\n\n // send the request either as a POST or GET\n this.xmlHttpChunkStart_ = 0;\n const useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();\n this.fetchResponseState_ = new FetchResponseState();\n // If the request is a GET request, start a backchannel to transfer streaming\n // data. Note that WebChannel GET request can also be used for closing the\n // channel as in method ChannelRequest#sendCloseRequest.\n // The second parameter of Channel#createXhrIo is JS only.\n this.xmlHttp_ = this.channel_.createXhrIo(\n useSecondaryDomains ? hostPrefix : null, !this.postData_);\n\n if (this.readyStateChangeThrottleMs_ > 0) {\n this.readyStateChangeThrottle_ = new goog.async.Throttle(\n goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),\n this.readyStateChangeThrottleMs_);\n }\n\n this.eventHandler_.listen(\n this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,\n this.readyStateChangeHandler_);\n\n const headers =\n this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};\n if (this.postData_) {\n if (!this.verb_) {\n this.verb_ = 'POST';\n }\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\n this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);\n } else {\n this.verb_ = 'GET';\n this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);\n }\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_MADE);\n this.channelDebug_.xmlHttpChannelRequest(\n this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);\n};\n\n\n/**\n * Handles a readystatechange event.\n * @param {goog.events.Event} evt The event.\n * @private\n */\nChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {\n 'use strict';\n const xhr = /** @type {goog.net.XhrIo} */ (evt.target);\n const throttle = this.readyStateChangeThrottle_;\n if (throttle &&\n xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n // Only throttle in the partial data case.\n this.channelDebug_.debug('Throttling readystatechange.');\n throttle.fire();\n } else {\n // If we haven't throttled, just handle response directly.\n this.xmlHttpHandler_(xhr);\n }\n};\n\n\n/**\n * XmlHttp handler\n * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.\n * @private\n */\nChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {\n 'use strict';\n requestStats.onStartExecution();\n\n try {\n if (xmlhttp == this.xmlHttp_) {\n this.onXmlHttpReadyStateChanged_();\n } else {\n this.channelDebug_.warning(\n 'Called back with an ' +\n 'unexpected xmlhttp');\n }\n } catch (ex) {\n this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');\n if (this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.dumpException(ex, function() {\n 'use strict';\n return 'ResponseText: ' + channelRequest.xmlHttp_.getResponseText();\n });\n } else {\n this.channelDebug_.dumpException(ex, 'No response text');\n }\n } finally {\n requestStats.onEndExecution();\n }\n};\n\n\n/**\n * Called by the readystate handler for XMLHTTP requests.\n *\n * @private\n */\nChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {\n 'use strict';\n const readyState = this.xmlHttp_.getReadyState();\n const errorCode = this.xmlHttp_.getLastErrorCode();\n const statusCode = this.xmlHttp_.getStatus();\n\n // we get partial results in browsers that support ready state interactive.\n // We also make sure that getResponseText is not null in interactive mode\n // before we continue.\n if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||\n (readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&\n !environment.isPollingRequired() && // otherwise, go on to startPolling\n !this.hasResponseBody_())) {\n return; // not yet ready\n }\n\n // Dispatch any appropriate network events.\n if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n errorCode != goog.net.ErrorCode.ABORT) {\n // Pretty conservative, these are the only known scenarios which we'd\n // consider indicative of a truly non-functional network connection.\n if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n } else {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_SUCCEEDED);\n }\n }\n\n // got some data so cancel the watchdog timer\n this.cancelWatchDogTimer_();\n\n const status = this.xmlHttp_.getStatus();\n this.lastStatusCode_ = status;\n const responseText = this.decodeXmlHttpResponse_();\n\n if (!this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'No response text for uri ' + channelRequest.requestUri_ +\n ' status ' + status;\n });\n }\n this.successful_ = (status == 200);\n\n this.channelDebug_.xmlHttpChannelResponseMetaData(\n /** @type {string} */ (this.verb_), this.requestUri_, this.rid_,\n this.retryId_, readyState, status);\n\n if (!this.successful_) {\n this.errorResponseHeaders_ = this.xmlHttp_.getResponseHeaders();\n if (status == 400 && responseText.indexOf('Unknown SID') > 0) {\n // the server error string will include 'Unknown SID' which indicates the\n // server doesn't know about the session (maybe it got restarted, maybe\n // the user got moved to another server, etc.,). Handlers can special\n // case this error\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');\n } else {\n this.lastError_ = ChannelRequest.Error.STATUS;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);\n this.channelDebug_.warning(\n 'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');\n }\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n\n if (this.shouldCheckInitialResponse_()) {\n const initialResponse = this.getInitialResponse_();\n if (initialResponse) {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, initialResponse,\n 'Initial handshake response via ' +\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n this.initialResponseDecoded_ = true;\n this.safeOnRequestData_(initialResponse);\n } else {\n this.successful_ = false;\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID; // fail-fast\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning(\n 'XMLHTTP Missing X_HTTP_INITIAL_RESPONSE' +\n ' (' + this.rid_ + ')');\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n }\n\n if (this.decodeChunks_) {\n this.decodeNextChunks_(readyState, responseText);\n if (environment.isPollingRequired() && this.successful_ &&\n readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n this.startPolling_();\n }\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, null);\n this.safeOnRequestData_(responseText);\n }\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.cleanup_();\n }\n\n if (!this.successful_) {\n return;\n }\n\n if (!this.cancelled_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.channel_.onRequestComplete(this);\n } else {\n // The default is false, the result from this callback shouldn't carry\n // over to the next callback, otherwise the request looks successful if\n // the watchdog timer gets called\n this.successful_ = false;\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Whether we need check the initial-response header that is sent during the\n * fast handshake.\n *\n * @return {boolean} true if the initial-response header is yet to be processed.\n * @private\n */\nChannelRequest.prototype.shouldCheckInitialResponse_ = function() {\n 'use strict';\n return this.decodeInitialResponse_ && !this.initialResponseDecoded_;\n};\n\n\n/**\n * Queries the initial response header that is sent during the handshake.\n *\n * @return {?string} The non-empty header value or null.\n * @private\n */\nChannelRequest.prototype.getInitialResponse_ = function() {\n 'use strict';\n if (this.xmlHttp_) {\n const value = this.xmlHttp_.getStreamingResponseHeader(\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n if (value && !goog.string.isEmptyOrWhitespace(value)) {\n return value;\n }\n }\n\n return null;\n};\n\n\n/**\n * Check if the initial response header has been handled.\n *\n * @return {boolean} true if X_HTTP_INITIAL_RESPONSE has been handled.\n */\nChannelRequest.prototype.isInitialResponseDecoded = function() {\n 'use strict';\n return this.initialResponseDecoded_;\n};\n\n\n/**\n * Decodes X_HTTP_INITIAL_RESPONSE if present.\n */\nChannelRequest.prototype.setDecodeInitialResponse = function() {\n 'use strict';\n this.decodeInitialResponse_ = true;\n};\n\n\n\n/**\n * Decodes the responses from XhrIo object.\n * @returns {string} responseText\n * @private\n */\nChannelRequest.prototype.decodeXmlHttpResponse_ = function() {\n 'use strict';\n if (!this.useFetchStreamsForResponse_()) {\n return this.xmlHttp_.getResponseText();\n }\n const responseChunks =\n /** @type {!Array<!Uint8Array>} */ (this.xmlHttp_.getResponse());\n let responseText = '';\n const responseLength = responseChunks.length;\n const requestCompleted =\n this.xmlHttp_.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n if (!this.fetchResponseState_.textDecoder) {\n if (typeof TextDecoder === 'undefined') {\n this.channelDebug_.severe(\n 'TextDecoder is not supported by this browser.');\n this.cleanup_();\n this.dispatchFailure_();\n return '';\n }\n this.fetchResponseState_.textDecoder = new goog.global.TextDecoder();\n }\n for (let i = 0; i < responseLength; i++) {\n this.fetchResponseState_.responseArrivedForFetch = true;\n const isLastChunk = requestCompleted && i == responseLength - 1;\n responseText += this.fetchResponseState_.textDecoder.decode(\n responseChunks[i], {stream: isLastChunk});\n }\n responseChunks.length = 0; // Empty the `responseChunks` array.\n this.fetchResponseState_.responseBuffer += responseText;\n this.xmlHttpChunkStart_ = 0;\n return this.fetchResponseState_.responseBuffer;\n};\n\n\n/**\n * Whether or not the response has response body.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.hasResponseBody_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n if (this.fetchResponseState_.responseArrivedForFetch) {\n return true;\n }\n return !(!this.xmlHttp_.getResponseText() && !this.xmlHttp_.getResponse());\n};\n\n/**\n * Whether or not the response body is streamed.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.useFetchStreamsForResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n return (\n this.verb_ == 'GET' && this.type_ != ChannelRequest.Type_.CLOSE_REQUEST &&\n this.channel_.usesFetchStreams());\n};\n\n\n/**\n * Decodes the next set of available chunks in the response.\n * @param {number} readyState The value of readyState.\n * @param {string} responseText The value of responseText.\n * @private\n */\nChannelRequest.prototype.decodeNextChunks_ = function(\n readyState, responseText) {\n 'use strict';\n let decodeNextChunksSuccessful = true;\n\n let chunkText;\n while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {\n chunkText = this.getNextChunk_(responseText);\n if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n // should have consumed entire response when the request is done\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);\n decodeNextChunksSuccessful = false;\n }\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, null, '[Incomplete Response]');\n break;\n } else if (chunkText == ChannelRequest.INVALID_CHUNK_) {\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunk]');\n decodeNextChunksSuccessful = false;\n break;\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, /** @type {string} */ (chunkText), null);\n this.safeOnRequestData_(/** @type {string} */ (chunkText));\n }\n }\n\n if (this.useFetchStreamsForResponse_() && this.xmlHttpChunkStart_ != 0) {\n // Remove processed chunk text from response buffer.\n this.fetchResponseState_.responseBuffer =\n this.fetchResponseState_.responseBuffer.slice(this.xmlHttpChunkStart_);\n this.xmlHttpChunkStart_ = 0;\n }\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n responseText.length == 0 &&\n !this.fetchResponseState_.responseArrivedForFetch) {\n // also an error if we didn't get any response\n this.lastError_ = ChannelRequest.Error.NO_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);\n decodeNextChunksSuccessful = false;\n }\n\n this.successful_ = this.successful_ && decodeNextChunksSuccessful;\n\n if (!decodeNextChunksSuccessful) {\n // malformed response - we make this trigger retry logic\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunked Response]');\n this.cleanup_();\n this.dispatchFailure_();\n } else {\n if (responseText.length > 0 && !this.firstByteReceived_) {\n this.firstByteReceived_ = true;\n this.channel_.onFirstByteReceived(this, responseText);\n }\n }\n};\n\n\n/**\n * Polls the response for new data.\n * @private\n */\nChannelRequest.prototype.pollResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return; // already closed\n }\n const readyState = this.xmlHttp_.getReadyState();\n const responseText = this.xmlHttp_.getResponseText();\n if (this.xmlHttpChunkStart_ < responseText.length) {\n this.cancelWatchDogTimer_();\n this.decodeNextChunks_(readyState, responseText);\n if (this.successful_ &&\n readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Starts a polling interval for changes to responseText of the\n * XMLHttpRequest, for browsers that don't fire onreadystatechange\n * as data comes in incrementally. This timer is disabled in\n * cleanup_().\n * @private\n */\nChannelRequest.prototype.startPolling_ = function() {\n 'use strict';\n this.eventHandler_.listen(\n this.pollingTimer_, goog.Timer.TICK, this.pollResponse_);\n this.pollingTimer_.start();\n};\n\n\n/**\n * Returns the next chunk of a chunk-encoded response. This is not standard\n * HTTP chunked encoding because browsers don't expose the chunk boundaries to\n * the application through XMLHTTP. So we have an additional chunk encoding at\n * the application level that lets us tell where the beginning and end of\n * individual responses are so that we can only try to eval a complete JS array.\n *\n * The encoding is the size of the chunk encoded as a decimal string followed\n * by a newline followed by the data.\n *\n * @param {string} responseText The response text from the XMLHTTP response.\n * @return {string|!Object} The next chunk string or a sentinel object\n * indicating a special condition.\n * @private\n */\nChannelRequest.prototype.getNextChunk_ = function(responseText) {\n 'use strict';\n const sizeStartIndex = this.xmlHttpChunkStart_;\n const sizeEndIndex = responseText.indexOf('\\n', sizeStartIndex);\n if (sizeEndIndex == -1) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex);\n const size = Number(sizeAsString);\n if (isNaN(size)) {\n return ChannelRequest.INVALID_CHUNK_;\n }\n\n const chunkStartIndex = sizeEndIndex + 1;\n if (chunkStartIndex + size > responseText.length) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const chunkText = responseText.slice(chunkStartIndex, chunkStartIndex + size);\n this.xmlHttpChunkStart_ = chunkStartIndex + size;\n return chunkText;\n};\n\n\n/**\n * Uses an IMG tag or navigator.sendBeacon to send an HTTP get to the server.\n *\n * This is only currently used to terminate the connection, as an IMG tag is\n * the most reliable way to send something to the server while the page\n * is getting torn down.\n *\n * Navigator.sendBeacon is available on Chrome and Firefox as a formal\n * solution to ensure delivery without blocking window close. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon\n *\n * For Chrome Apps, sendBeacon is always necessary due to Content Security\n * Policy (CSP) violation of using an IMG tag.\n *\n * For react-native, we use xhr to send the actual close request, and assume\n * there is no page-close issue with react-native.\n *\n * @param {goog.Uri} uri The uri to send a request to.\n */\nChannelRequest.prototype.sendCloseRequest = function(uri) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.CLOSE_REQUEST;\n this.baseUri_ = uri.clone().makeUnique();\n\n let requestSent = false;\n\n if (goog.global.navigator && goog.global.navigator.sendBeacon) {\n try {\n // empty string body to avoid 413 error on chrome < 41\n requestSent =\n goog.global.navigator.sendBeacon(this.baseUri_.toString(), '');\n } catch {\n // Intentionally left empty; sendBeacon might throw TypeError in certain\n // unexpected cases.\n }\n }\n\n if (!requestSent && goog.global.Image) {\n const eltImg = new Image();\n eltImg.src = this.baseUri_;\n requestSent = true;\n }\n\n if (!requestSent) {\n // no handler is set to match the sendBeacon/Image behavior\n this.xmlHttp_ = this.channel_.createXhrIo(null);\n this.xmlHttp_.send(this.baseUri_);\n }\n\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n};\n\n\n/**\n * Cancels the request no matter what the underlying transport is.\n */\nChannelRequest.prototype.cancel = function() {\n 'use strict';\n this.cancelled_ = true;\n this.cleanup_();\n};\n\n\n/**\n * Resets the timeout.\n *\n * @param {number=} opt_timeout The new timeout\n */\nChannelRequest.prototype.resetTimeout = function(opt_timeout) {\n 'use strict';\n if (opt_timeout) {\n this.setTimeout(opt_timeout);\n }\n // restart only if a timer is currently set\n if (this.watchDogTimerId_) {\n this.cancelWatchDogTimer_();\n this.ensureWatchDogTimer_();\n }\n};\n\n\n/**\n * Ensures that there is watchdog timeout which is used to ensure that\n * the connection completes in time.\n *\n * @private\n */\nChannelRequest.prototype.ensureWatchDogTimer_ = function() {\n 'use strict';\n this.watchDogTimeoutTime_ = Date.now() + this.timeout_;\n this.startWatchDogTimer_(this.timeout_);\n};\n\n\n/**\n * Starts the watchdog timer which is used to ensure that the connection\n * completes in time.\n * @param {number} time The number of milliseconds to wait.\n * @private\n */\nChannelRequest.prototype.startWatchDogTimer_ = function(time) {\n 'use strict';\n if (this.watchDogTimerId_ != null) {\n // assertion\n throw new Error('WatchDog timer not null');\n }\n this.watchDogTimerId_ =\n requestStats.setTimeout(goog.bind(this.onWatchDogTimeout_, this), time);\n};\n\n\n/**\n * Cancels the watchdog timer if it has been started.\n *\n * @private\n */\nChannelRequest.prototype.cancelWatchDogTimer_ = function() {\n 'use strict';\n if (this.watchDogTimerId_) {\n goog.global.clearTimeout(this.watchDogTimerId_);\n this.watchDogTimerId_ = null;\n }\n};\n\n\n/**\n * Called when the watchdog timer is triggered. It also handles a case where it\n * is called too early which we suspect may be happening sometimes\n * (not sure why)\n *\n * @private\n */\nChannelRequest.prototype.onWatchDogTimeout_ = function() {\n 'use strict';\n this.watchDogTimerId_ = null;\n const now = Date.now();\n goog.asserts.assert(\n this.watchDogTimeoutTime_, 'WatchDog timeout time missing?');\n if (now - this.watchDogTimeoutTime_ >= 0) {\n this.handleTimeout_();\n } else {\n // got called too early for some reason\n this.channelDebug_.warning('WatchDog timer called too early');\n this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now);\n }\n};\n\n\n/**\n * Called when the request has actually timed out. Will cleanup and notify the\n * channel of the failure.\n *\n * @private\n */\nChannelRequest.prototype.handleTimeout_ = function() {\n 'use strict';\n if (this.successful_) {\n // Should never happen.\n this.channelDebug_.severe(\n 'Received watchdog timeout even though request loaded successfully');\n }\n\n this.channelDebug_.timeoutResponse(this.requestUri_);\n\n // IMG or SendBeacon requests never notice if they were successful,\n // and always 'time out'. This fact says nothing about reachability.\n if (this.type_ != ChannelRequest.Type_.CLOSE_REQUEST) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_TIMEOUT);\n }\n\n this.cleanup_();\n\n // Set error and dispatch failure.\n // This is called for CLOSE_REQUEST too to ensure channel_.onRequestComplete.\n this.lastError_ = ChannelRequest.Error.TIMEOUT;\n this.dispatchFailure_();\n};\n\n\n/**\n * Notifies the channel that this request failed.\n * @private\n */\nChannelRequest.prototype.dispatchFailure_ = function() {\n 'use strict';\n if (this.channel_.isClosed() || this.cancelled_) {\n return;\n }\n\n this.channel_.onRequestComplete(this);\n};\n\n\n/**\n * Cleans up the objects used to make the request. This function is\n * idempotent.\n *\n * @private\n */\nChannelRequest.prototype.cleanup_ = function() {\n 'use strict';\n this.cancelWatchDogTimer_();\n\n goog.dispose(this.readyStateChangeThrottle_);\n this.readyStateChangeThrottle_ = null;\n\n // Stop the polling timer, if necessary.\n this.pollingTimer_.stop();\n\n // Unhook all event handlers.\n this.eventHandler_.removeAll();\n\n if (this.xmlHttp_) {\n // clear out this.xmlHttp_ before aborting so we handle getting reentered\n // inside abort\n const xmlhttp = this.xmlHttp_;\n this.xmlHttp_ = null;\n xmlhttp.abort();\n xmlhttp.dispose();\n }\n};\n\n\n/**\n * Indicates whether the request was successful. Only valid after the handler\n * is called to indicate completion of the request.\n *\n * @return {boolean} True if the request succeeded.\n */\nChannelRequest.prototype.getSuccess = function() {\n 'use strict';\n return this.successful_;\n};\n\n\n/**\n * If the request was not successful, returns the reason.\n *\n * @return {?ChannelRequest.Error} The last error.\n */\nChannelRequest.prototype.getLastError = function() {\n 'use strict';\n return this.lastError_;\n};\n\n\n/**\n * @return {!Object<string, string>|undefined} Response headers received\n * along with the non-200 status, as a key-value map.\n */\nChannelRequest.prototype.getErrorResponseHeaders = function() {\n 'use strict';\n return this.errorResponseHeaders_;\n};\n\n\n/**\n * Returns the status code of the last request.\n *\n * @return {number} The status code of the last request.\n */\nChannelRequest.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.lastStatusCode_;\n};\n\n\n/**\n * Returns the session id for this channel.\n *\n * @return {string|undefined} The session ID.\n */\nChannelRequest.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Returns the request id for this request. Each request has a unique request\n * id and the request IDs are a sequential increasing count.\n *\n * @return {string|number|undefined} The request ID.\n */\nChannelRequest.prototype.getRequestId = function() {\n 'use strict';\n return this.rid_;\n};\n\n\n/**\n * Returns the data for a post, if this request is a post.\n *\n * @return {?string} The POST data provided by the request initiator.\n */\nChannelRequest.prototype.getPostData = function() {\n 'use strict';\n return this.postData_;\n};\n\n\n/**\n * Returns the XhrIo request object.\n *\n * @return {?goog.net.XhrIo} Any XhrIo request created for this object.\n */\nChannelRequest.prototype.getXhr = function() {\n 'use strict';\n return this.xmlHttp_;\n};\n\n\n/**\n * Returns the time that the request started, if it has started.\n *\n * @return {?number} The time the request started, as returned by Date.now().\n */\nChannelRequest.prototype.getRequestStartTime = function() {\n 'use strict';\n return this.requestStartTime_;\n};\n\n\n/**\n * Helper to call the callback's onRequestData, which catches any\n * exception.\n * @param {string} data The request data.\n * @private\n */\nChannelRequest.prototype.safeOnRequestData_ = function(data) {\n 'use strict';\n try {\n this.channel_.onRequestData(this, data);\n const stats = requestStats.ServerReachability;\n requestStats.notifyServerReachabilityEvent(stats.BACK_CHANNEL_ACTIVITY);\n } catch (e) {\n // Dump debug info, but keep going without closing the channel.\n this.channelDebug_.dumpException(e, 'Error in httprequest callback');\n }\n};\n\n\n/**\n * Convenience factory method.\n *\n * @param {Channel} channel The channel object that owns this request.\n * @param {WebChannelDebug} channelDebug A WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @return {!ChannelRequest} The created channel request.\n */\nChannelRequest.createChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n return new ChannelRequest(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A single module to define user-agent specific environment\n * details.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.environment');\n\ngoog.module.declareLegacyNamespace();\n\nvar userAgent = goog.require('goog.userAgent');\n\n\n/**\n * The default polling interval in millis for Edge.\n *\n * Currently on edge, new-chunk events may be not be fired (at all) if a new\n * chunk arrives within 50ms following the previous chunk. This may be fixed\n * in future, which requires changes to the whatwg spec too.\n *\n * @private @const {number}\n */\nvar EDGE_POLLING_INTERVAL_ = 125;\n\n\n/**\n * History:\n *\n * IE11 is still using Trident, the traditional engine for IE.\n * Edge is using EdgeHTML, a fork of Trident. We are seeing the same issue\n * on IE-11 (reported in 2017), so treat IE the same as Edge for now.\n *\n * We used to do polling for Opera (only) with an 250ms interval, because Opera\n * only fires readyState == INTERACTIVE once. Opera switched to WebKit in 2013,\n * and then to Blink (chrome).\n *\n * TODO(user): check the raw UA string to keep polling for old, mobile operas\n * that may still be affected. For old Opera, double the polling interval\n * to 250ms.\n *\n * @return {boolean} True if polling is required with XHR.\n */\nexports.isPollingRequired = function() {\n return userAgent.EDGE_OR_IE;\n};\n\n\n/**\n * How often to poll (in MS) for changes to responseText in browsers that don't\n * fire onreadystatechange during incremental loading of the response body.\n *\n * @return {number|undefined} The polling interval (MS) for the current U-A;\n * or undefined if polling is not supposed to be enabled.\n */\nexports.getPollingInterval = function() {\n if (userAgent.EDGE_OR_IE) {\n return EDGE_POLLING_INTERVAL_;\n }\n\n return undefined;\n};\n\n/**\n * Origin trial token for google.com\n *\n * https://developers.chrome.com/origintrials/#/trials\n *\n * http://googlechrome.github.io/OriginTrials/check-token.html\n * Origin: https://google.com:443\n * Matches Subdomains? Yes\n * Matches Third-party? Yes\n * Feature: FetchUploadStreaming\n * Up to Chrome 95 (ends with the rollout of next Chrome release), no later\n * than Nov 9, 2021\n *\n * Token for googleapis.com will be registered after google.com's is deployed.\n *\n */\nconst OT_TOKEN_GOOGLE_COM =\n 'A0eNbltY1nd4MP7XTHXnTxWogDL6mWTdgIIKfKOTJoUHNbFFMZQBoiHHjJ9UK9lgYndWFaxOWR7ld8uUjcWmcwIAAAB/eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IkZldGNoVXBsb2FkU3RyZWFtaW5nIiwiZXhwaXJ5IjoxNjM2NTAyMzk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ==';\n\n\n/**\n * Creates ReadableStream to upload\n * @return {!ReadableStream} ReadableStream to upload\n */\nfunction createStream() {\n const encoder = new goog.global.TextEncoder();\n return new goog.global.ReadableStream({\n start: controller => {\n for (const obj of ['test\\r\\n', 'test\\r\\n']) {\n controller.enqueue(encoder.encode(obj));\n }\n controller.close();\n }\n });\n}\n\n/**\n * Detect the user agent is chrome and its version is higher than M90.\n * This code is hard-coded from goog.labs.userAgent.browser to avoid file size\n * increasing.\n * @return {boolean} Whether the above is true.\n */\nfunction isChromeM90OrHigher() {\n const userAgentStr = function() {\n const navigator = goog.global.navigator;\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n }();\n\n const matchUserAgent = function(str) {\n return userAgentStr.indexOf(str) != -1;\n };\n\n if (!matchUserAgent('Chrome') || matchUserAgent('Edg')) {\n return false;\n }\n\n const match = /Chrome\\/(\\d+)/.exec(userAgentStr);\n const chromeVersion = parseInt(match[1], 10);\n return chromeVersion >= 90;\n}\n\n/**\n * Detect the URL origin is *.google.com.\n * @param {string} url The target URL.\n * @return {boolean} Whether the above is true.\n */\nfunction isUrlGoogle(url) {\n const match = /\\/\\/([^\\/]+)\\//.exec(url);\n if (!match) {\n return false;\n }\n const origin = match[1];\n return origin.endsWith('google.com');\n}\n\n/**\n * The flag to run the origin trials code only once.\n */\nlet isStartOriginTrialsCalled = false;\n\n/**\n * For Fetch/upload OT, make three requests against the server endpoint.\n * POST requests contain only dummy payload.\n *\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * This function is expected to be called from background during the handshake.\n * Exceptions will be logged by the caller.\n *\n * No stats or logs are collected on the client-side. To be disabled once the\n * OT is expired.\n *\n * @param {string} path The base URL path for the requests\n * @param {function(*)} logError A function to execute when exceptions are\n * caught.\n */\nexports.startOriginTrials = function(path, logError) {\n if (isStartOriginTrialsCalled) {\n return;\n }\n isStartOriginTrialsCalled = true;\n // NE: may need check if path has already contains query params?\n\n // Accept only Chrome M90 or later due to service worker support.\n if (!isChromeM90OrHigher()) {\n return;\n }\n\n // Accept only only google.com and subdoamins.\n if (!isUrlGoogle(path)) {\n return;\n }\n // Since 3P OT is not supported yet, we should check the current page matches\n // the path (absolute one?) to disable this OT for cross-origin calls\n if (!window || !window.document || !isUrlGoogle(window.document.URL)) {\n return;\n }\n\n // Enable origin trial by injecting OT <meta> tag\n const tokenElement =\n /** @type {! HTMLMetaElement} */ (document.createElement('meta'));\n tokenElement.httpEquiv = 'origin-trial';\n tokenElement.content = OT_TOKEN_GOOGLE_COM;\n // appendChild() synchronously enables OT.\n document.head.appendChild(tokenElement);\n\n // Check if fetch upload stream is actually enabled.\n // By the spec, Streaming request doesn't has the Content-Type header:\n // https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n // If Chrome doesn't support Streaming, the body stream is converted to a\n // string \"[object ReadableStream]\" for fallback then it has \"Content-Type:\n // text/plain;charset=UTF-8\".\n const supportsRequestStreams = !new Request('', {\n body: new ReadableStream(),\n method: 'POST',\n }).headers.has('Content-Type');\n\n if (supportsRequestStreams) {\n logError('OriginTrial unexpected.');\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Base WebChannel implementation.\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBase');\n\ngoog.require('goog.Uri');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.async.run');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.ConnectionState');\ngoog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.labs.net.webChannel.WireV8');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.netUtils');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XhrIo');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.require('goog.net.rpc.HttpCors');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.structs');\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst ConnectionState = goog.labs.net.webChannel.ConnectionState;\nconst ForwardChannelRequestPool =\n goog.labs.net.webChannel.ForwardChannelRequestPool;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst Wire = goog.labs.net.webChannel.Wire;\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst environment = goog.labs.net.webChannel.environment;\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\nconst httpCors = goog.module.get('goog.net.rpc.HttpCors');\n\n/**\n * @define {boolean} If WebChannel should compile with Origin Trial features.\n */\nconst ALLOW_ORIGIN_TRIAL_FEATURES =\n goog.define('goog.net.webChannel.ALLOW_ORIGIN_TRIAL_FEATURES', false);\n\n/**\n * @define {boolean} If webchannel should ping google.com for debugging\n * connectivity issues (that may have caused the channel to abort).\n */\nconst ENABLE_GOOGLE_COM_PING =\n goog.define('goog.net.webChannel.ENABLE_GOOGLE_COM_PING', true);\n\n/**\n * Gets an internal channel parameter in a type-safe way.\n *\n * @param {string} paramName the key of the parameter to fetch.\n * @param {!T} defaultValue the default value to return\n * @param {!goog.net.WebChannel.Options=} options Configuration for the\n * WebChannel instance.\n * @return {T}\n * @template T\n */\nfunction getInternalChannelParam(paramName, defaultValue, options) {\n if (!options || !options.internalChannelParams) {\n return defaultValue;\n }\n return /** @type {T} */ (options.internalChannelParams[paramName]) ||\n defaultValue;\n}\n\n/**\n * This WebChannel implementation is branched off goog.net.BrowserChannel\n * for now. Ongoing changes to goog.net.BrowserChannel will be back\n * ported to this implementation as needed.\n *\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * WebChannel instance.\n * @param {number=} opt_clientVersion An application-specific version number\n * that is sent to the server when connected.\n * @param {!ConnectionState=} opt_conn Previously determined connection\n * conditions.\n * @constructor\n * @struct\n * @implements {goog.labs.net.webChannel.Channel}\n */\ngoog.labs.net.webChannel.WebChannelBase = function(\n opt_options, opt_clientVersion, opt_conn) {\n 'use strict';\n /**\n * The client library version (capabilities).\n * @private {number}\n */\n this.clientVersion_ = opt_clientVersion || 0;\n\n /**\n * The server library version (capabilities).\n * @private {number}\n */\n this.serverVersion_ = 0;\n\n\n /**\n * An array of queued maps that need to be sent to the server.\n * @private {!Array<Wire.QueuedMap>}\n */\n this.outgoingMaps_ = [];\n\n /**\n * The channel debug used for logging\n * @private {!WebChannelDebug}\n */\n this.channelDebug_ = new WebChannelDebug();\n\n /**\n * Connectivity state.\n * @private {!ConnectionState}\n */\n this.connState_ = opt_conn || new ConnectionState();\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n /**\n * Extra HTTP headers to add to the init request(s) sent to the server.\n * @private {?Object}\n */\n this.initHeaders_ = null;\n\n /**\n * @private {?string} The URL param name to overwrite custom HTTP headers\n * to bypass CORS preflight.\n */\n this.httpHeadersOverwriteParam_ = null;\n\n /**\n * Extra parameters to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraParams_ = null;\n\n /**\n * Parameter name for the http session id.\n * @private {?string}\n */\n this.httpSessionIdParam_ = null;\n\n /**\n * The http session id, to be sent with httpSessionIdParam_ with each\n * request after the initial handshake.\n * @private {?string}\n */\n this.httpSessionId_ = null;\n\n /**\n * The ChannelRequest object for the backchannel.\n * @private {?ChannelRequest}\n */\n this.backChannelRequest_ = null;\n\n /**\n * The relative path (in the context of the page hosting the browser channel)\n * for making requests to the server.\n * @private {?string}\n */\n this.path_ = null;\n\n /**\n * The absolute URI for the forwardchannel request.\n * @private {?goog.Uri}\n */\n this.forwardChannelUri_ = null;\n\n /**\n * The absolute URI for the backchannel request.\n * @private {?goog.Uri}\n */\n this.backChannelUri_ = null;\n\n /**\n * A subdomain prefix for using a subdomain in IE for the backchannel\n * requests.\n * @private {?string}\n */\n this.hostPrefix_ = null;\n\n /**\n * Whether we allow the use of a subdomain in IE for the backchannel requests.\n * @private {boolean}\n */\n this.allowHostPrefix_ = true;\n\n /**\n * The next id to use for the RID (request identifier) parameter. This\n * identifier uniquely identifies the forward channel request.\n * @private {number}\n */\n this.nextRid_ = 0;\n\n /**\n * The id to use for the next outgoing map. This identifier uniquely\n * identifies a sent map.\n * @private {number}\n */\n this.nextMapId_ = 0;\n\n /**\n * Whether to fail forward-channel requests after one try or a few tries.\n * @private {boolean}\n */\n this.failFast_ = getInternalChannelParam('failFast', false, opt_options);\n\n /**\n * The handler that receive callbacks for state changes and data.\n * @private {?goog.labs.net.webChannel.WebChannelBase.Handler}\n */\n this.handler_ = null;\n\n /**\n * Timer identifier for asynchronously making a forward channel request.\n * This is set to true if the func is scheduled with async.run, which\n * is equivalent to setTimeout(0).\n * @private {?number|?boolean}\n */\n this.forwardChannelTimerId_ = null;\n\n /**\n * Timer identifier for asynchronously making a back channel request.\n * @private {?number}\n */\n this.backChannelTimerId_ = null;\n\n /**\n * Timer identifier for the timer that waits for us to retry the backchannel\n * in the case where it is dead and no longer receiving data.\n * @private {?number}\n */\n this.deadBackChannelTimerId_ = null;\n\n /**\n * Whether the client's network conditions can support streamed responses.\n * @private {?boolean}\n */\n this.enableStreaming_ = null;\n\n /**\n * Whether streaming mode is allowed. In certain debugging situations, it's\n * useful to disable this.\n * @private {boolean}\n */\n this.allowStreamingMode_ = true;\n\n /**\n * The array identifier of the last array received from the server for the\n * backchannel request.\n * @private {number}\n */\n this.lastArrayId_ = -1;\n\n /**\n * The array id of the last array sent by the server that we know about.\n * @private {number}\n */\n this.lastPostResponseArrayId_ = -1;\n\n /**\n * The non-200 status code received that causes the channel to be aborted.\n * @private {number}\n */\n this.errorResponseStatusCode_ = -1;\n\n /**\n * The response headers received along with the non-200 status.\n * @private {!Object<string, string>|undefined}\n */\n this.errorResponseHeaders_ = undefined;\n\n /**\n * Number of times we have retried the current forward channel request.\n * @private {number}\n */\n this.forwardChannelRetryCount_ = 0;\n\n /**\n * Number of times in a row that we have retried the current back channel\n * request and received no data.\n * @private {number}\n */\n this.backChannelRetryCount_ = 0;\n\n /**\n * The attempt id for the current back channel request. Starts at 1 and\n * increments for each reconnect. The server uses this to log if our\n * connection is flaky or not.\n * @private {number}\n */\n this.backChannelAttemptId_ = 0;\n\n /**\n * The base part of the time before firing next retry request. Default is 5\n * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_})\n * for all retries, and linear backoff is applied to the sum for subsequent\n * retries.\n * @private {number}\n */\n this.baseRetryDelayMs_ =\n getInternalChannelParam('baseRetryDelayMs', 5 * 1000, opt_options);\n\n /**\n * A random time between 0 and this number of MS is added to the\n * {@link baseRetryDelayMs_}. Default is 10 seconds.\n * @private {number}\n */\n this.retryDelaySeedMs_ =\n getInternalChannelParam('retryDelaySeedMs', 10 * 1000, opt_options);\n\n /**\n * Maximum number of attempts to connect to the server for forward channel\n * requests. Defaults to 2.\n * @private {number}\n */\n this.forwardChannelMaxRetries_ =\n getInternalChannelParam('forwardChannelMaxRetries', 2, opt_options);\n\n /**\n * The timeout in milliseconds for a forward channel request. Defaults to 20\n * seconds. Note that part of this timeout can be randomized.\n * @private {number}\n */\n this.forwardChannelRequestTimeoutMs_ = getInternalChannelParam(\n 'forwardChannelRequestTimeoutMs', 20 * 1000, opt_options);\n\n /**\n * The custom factory used to create XMLHttpRequest objects.\n * @private {!goog.net.XmlHttpFactory | undefined}\n */\n this.xmlHttpFactory_ =\n (opt_options && opt_options.xmlHttpFactory) || undefined;\n\n /**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @private {boolean}\n */\n this.usesFetchStreams_ =\n (opt_options && opt_options.useFetchStreams) || false;\n\n /**\n * The timeout in milliseconds for a back channel request. Defaults to using\n * the timeout configured in ChannelRequest (45s). If server-side\n * keepaliveInterval is known to the client, set the backchannel request\n * timeout to 1.5 * keepaliveInterval (ms).\n *\n * @private {number|undefined}\n */\n this.backChannelRequestTimeoutMs_ = undefined;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n *\n * This throttle is useful if the server sends large data chunks down the\n * backchannel. It prevents examining XHR partial data on every readystate\n * change event. This is useful because large chunks can trigger hundreds\n * of readystatechange events, each of which takes ~5ms or so to handle,\n * in turn making the UI unresponsive for a significant period.\n *\n * If set to zero no throttle is used.\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * Whether cross origin requests are supported for the channel.\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @private {boolean}\n */\n this.supportsCrossDomainXhrs_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * The current session id.\n * @private {string}\n */\n this.sid_ = '';\n\n /**\n * The current ChannelRequest pool for the forward channel.\n * @private {!ForwardChannelRequestPool}\n */\n this.forwardChannelRequestPool_ = new ForwardChannelRequestPool(\n opt_options && opt_options.concurrentRequestLimit);\n\n /**\n * The V8 codec.\n * @private {!WireV8}\n */\n this.wireCodec_ = new WireV8();\n\n /**\n * Whether to turn on the fast handshake behavior.\n *\n * @private {boolean}\n */\n this.fastHandshake_ = (opt_options && opt_options.fastHandshake) || false;\n\n /**\n * Whether to encode initMessageHeaders in the body.\n *\n * @private {boolean}\n */\n this.encodeInitMessageHeaders_ =\n (opt_options && opt_options.encodeInitMessageHeaders) || false;\n\n if (this.fastHandshake_ && this.encodeInitMessageHeaders_) {\n this.channelDebug_.warning(\n 'Ignore encodeInitMessageHeaders because fastHandshake is set.');\n this.encodeInitMessageHeaders_ = false;\n }\n\n /**\n * Whether to signal to the server to enable blocking handshake.\n *\n * @private {boolean}\n */\n this.blockingHandshake_ =\n (opt_options && opt_options.blockingHandshake) || false;\n\n\n if (opt_options && opt_options.disableRedact) {\n this.channelDebug_.disableRedact();\n }\n\n if (opt_options && opt_options.forceLongPolling) {\n this.allowStreamingMode_ = false;\n }\n\n /**\n * Whether to detect buffering proxies.\n *\n * fastHandshake + detectBufferingProxy are yet to be implemented.\n *\n * @private {boolean}\n */\n this.detectBufferingProxy_ =\n (!this.fastHandshake_ && this.allowStreamingMode_ && opt_options &&\n opt_options.detectBufferingProxy) ||\n false;\n\n /**\n * Long polling timeout interval for the server to complete the handing GET.\n *\n * @private {number|undefined}\n */\n this.longPollingTimeout_ = undefined;\n\n if (opt_options && opt_options.longPollingTimeout &&\n opt_options.longPollingTimeout > 0) {\n this.longPollingTimeout_ = opt_options.longPollingTimeout;\n }\n\n /**\n * Callback when all the pending client-sent messages have been flushed.\n *\n * @private {function()|undefined}\n */\n this.forwardChannelFlushedCallback_ = undefined;\n\n /**\n * TODO(user): move all backchannel states to its own class similar to\n * forwardchannelrequestpool.js and log more stats.\n *\n * The estimated handshake RTT (ms) as measured from when the handshake\n * request is sent and when the handshake response headers are received.\n * If the value is 0, the RTT is unknown.\n *\n * @private {number}\n */\n this.handshakeRttMs_ = 0;\n\n /**\n * If BP detection is done or still in progress.\n * Should only be checked when detectBufferingProxy is turned on.\n * @private {boolean}\n */\n this.bpDetectionDone_ = false;\n\n /**\n * The timer for detecting buffering proxy. This needs be reset with each\n * backchannel request. If this is not null, bpDetectionDone_ == false.\n * @private {?number}\n */\n this.bpDetectionTimerId_ = null;\n\n /***\n * Whether to attempt Chrome Origin Trials as part of the handshake.\n * @private @const {boolean}\n */\n this.enableOriginTrials_ = ALLOW_ORIGIN_TRIAL_FEATURES &&\n (!opt_options || opt_options.enableOriginTrials !== false);\n\n /**\n * The array of non-acked maps at the time of channel close. Refer to\n * `getNonAckedMessagesWithClosedChannel()` API for definitions of non-acked\n * messages.\n *\n * @private {?Array<!Wire.QueuedMap>}\n */\n this.nonAckedMapsAtChannelClose_ = null;\n};\n\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\n\n\n/**\n * The channel version that we negotiated with the server for this session.\n * Starts out as the version we request, and then is changed to the negotiated\n * version after the initial open.\n * @private {number}\n */\nWebChannelBase.prototype.channelVersion_ = Wire.LATEST_CHANNEL_VERSION;\n\n\n/**\n * Enum type for the channel state machine.\n * @enum {number}\n */\nWebChannelBase.State = {\n /** The channel is closed. */\n CLOSED: 0,\n\n /** The channel has been initialized but hasn't yet initiated a connection. */\n INIT: 1,\n\n /** The channel is in the process of opening a connection to the server. */\n OPENING: 2,\n\n /** The channel is open. */\n OPENED: 3\n};\n\n\n/**\n * The current state of the WebChannel.\n * @private {!WebChannelBase.State}\n */\nWebChannelBase.prototype.state_ = WebChannelBase.State.INIT;\n\n\n/**\n * The timeout in milliseconds for a forward channel request.\n * @type {number}\n */\nWebChannelBase.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000;\n\n\n/**\n * Maximum number of attempts to connect to the server for back channel\n * requests.\n * @type {number}\n */\nWebChannelBase.BACK_CHANNEL_MAX_RETRIES = 3;\n\n\n/**\n * A number in MS of how long we guess the maxmium amount of time a round trip\n * to the server should take. In the future this could be substituted with a\n * real measurement of the RTT.\n * @type {number}\n */\nWebChannelBase.RTT_ESTIMATE = 3 * 1000;\n\n\n/**\n * When retrying for an inactive channel, we will multiply the total delay by\n * this number.\n * @type {number}\n */\nWebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR = 2;\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nWebChannelBase.Error = {\n /** Value that indicates no error has occurred. */\n OK: 0,\n\n /** An error due to a request failing. */\n REQUEST_FAILED: 2,\n\n /** An error due to the user being logged out. */\n LOGGED_OUT: 4,\n\n /** An error due to server response which contains no data. */\n NO_DATA: 5,\n\n /** An error due to a server response indicating an unknown session id */\n UNKNOWN_SESSION_ID: 6,\n\n /** An error due to a server response requesting to stop the channel. */\n STOP: 7,\n\n /** A general network error. */\n NETWORK: 8,\n\n /** An error due to bad data being returned from the server. */\n BAD_DATA: 10,\n\n /** An error due to a response that is not parsable. */\n BAD_RESPONSE: 11\n};\n\n\n/**\n * Internal enum type for the two channel types.\n * @enum {number}\n * @private\n */\nWebChannelBase.ChannelType_ = {\n FORWARD_CHANNEL: 1,\n\n BACK_CHANNEL: 2\n};\n\n\n/**\n * The maximum number of maps that can be sent in one POST. Should match\n * MAX_MAPS_PER_REQUEST on the server code.\n * @type {number}\n * @private\n */\nWebChannelBase.MAX_MAPS_PER_REQUEST_ = 1000;\n\n\n/**\n * The maximum number of utf-8 chars that can be sent in one GET to enable 0-RTT\n * handshake.\n *\n * @const @private {number}\n */\nWebChannelBase.MAX_CHARS_PER_GET_ = 4 * 1024;\n\n\n/**\n * A guess at a cutoff at which to no longer assume the backchannel is dead\n * when we are slow to receive data. Number in bytes.\n *\n * Assumption: The worst bandwidth we work on is 50 kilobits/sec\n * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout\n * @type {number}\n */\nWebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500;\n\n\n/**\n * @return {number} The server version or 0 if undefined\n */\nWebChannelBase.prototype.getServerVersion = function() {\n 'use strict';\n return this.serverVersion_;\n};\n\n\n/**\n * @return {!ForwardChannelRequestPool} The forward channel request pool.\n */\nWebChannelBase.prototype.getForwardChannelRequestPool = function() {\n 'use strict';\n return this.forwardChannelRequestPool_;\n};\n\n\n/**\n * @return {!Object} The codec object.\n */\nWebChannelBase.prototype.getWireCodec = function() {\n 'use strict';\n return this.wireCodec_;\n};\n\n\n/**\n * Returns the logger.\n *\n * @return {!WebChannelDebug} The channel debug object.\n */\nWebChannelBase.prototype.getChannelDebug = function() {\n 'use strict';\n return this.channelDebug_;\n};\n\n\n/**\n * Sets the logger.\n *\n * @param {!WebChannelDebug} channelDebug The channel debug object.\n */\nWebChannelBase.prototype.setChannelDebug = function(channelDebug) {\n 'use strict';\n this.channelDebug_ = channelDebug;\n};\n\n\n/**\n * Starts the channel. This initiates connections to the server.\n *\n * @param {string} channelPath The path for the channel connection.\n * @param {!Object=} opt_extraParams Extra parameter keys and values to add to\n * the requests.\n * @param {string=} opt_oldSessionId Session ID from a previous session.\n * @param {number=} opt_oldArrayId The last array ID from a previous session.\n */\nWebChannelBase.prototype.connect = function(\n channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) {\n 'use strict';\n this.channelDebug_.debug('connect()');\n\n this.startOriginTrials_(channelPath);\n\n requestStats.notifyStatEvent(requestStats.Stat.CONNECT_ATTEMPT);\n\n this.path_ = channelPath;\n this.extraParams_ = opt_extraParams || {};\n\n // Attach parameters about the previous session if reconnecting.\n if (opt_oldSessionId && opt_oldArrayId !== undefined) {\n this.extraParams_['OSID'] = opt_oldSessionId;\n this.extraParams_['OAID'] = opt_oldArrayId;\n }\n\n this.enableStreaming_ = this.allowStreamingMode_;\n this.connectChannel_();\n};\n\n\n/**\n * Disconnects and closes the channel.\n */\nWebChannelBase.prototype.disconnect = function() {\n 'use strict';\n this.channelDebug_.debug('disconnect()');\n\n this.cancelRequests_();\n\n if (this.state_ == WebChannelBase.State.OPENED) {\n const rid = this.nextRid_++;\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('TYPE', 'terminate');\n\n this.addAdditionalParams_(uri);\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid);\n request.sendCloseRequest(uri);\n }\n\n this.onClose_();\n};\n\n\n/**\n * Returns the session id of the channel. Only available after the\n * channel has been opened.\n * @return {string} Session ID.\n */\nWebChannelBase.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Starts the connection.\n * @private\n */\nWebChannelBase.prototype.connectChannel_ = function() {\n 'use strict';\n this.channelDebug_.debug('connectChannel_()');\n this.ensureInState_(WebChannelBase.State.INIT, WebChannelBase.State.CLOSED);\n this.forwardChannelUri_ =\n this.getForwardChannelUri(/** @type {string} */ (this.path_));\n this.ensureForwardChannel_();\n};\n\n\n/**\n * Starts the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.startOriginTrials_ = function(channelPath) {\n 'use strict';\n\n if (!this.enableOriginTrials_) {\n return;\n }\n\n this.channelDebug_.info('Origin Trials enabled.');\n goog.async.run(goog.bind(this.runOriginTrials_, this, channelPath));\n};\n\n\n/**\n * Runs the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.runOriginTrials_ = function(channelPath) {\n 'use strict';\n\n try {\n // Since startOriginTrials might throw exceptions asynchronously, we should\n // capture it in promise-catch.\n environment.startOriginTrials(channelPath, e => {\n this.channelDebug_.dumpException(\n /** @type {?Error} */ (e), 'Error in running origin trials');\n });\n this.channelDebug_.info('Origin Trials invoked: ' + channelPath);\n } catch (e) {\n this.channelDebug_.dumpException(e, 'Error in running origin trials');\n }\n};\n\n\n/**\n * Cancels backchannel request.\n * @private\n */\nWebChannelBase.prototype.cancelBackChannelRequest_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n this.clearBpDetectionTimer_();\n this.backChannelRequest_.cancel();\n this.backChannelRequest_ = null;\n }\n};\n\n\n/**\n * Cancels all outstanding requests.\n * @private\n */\nWebChannelBase.prototype.cancelRequests_ = function() {\n 'use strict';\n this.cancelBackChannelRequest_();\n\n if (this.backChannelTimerId_) {\n goog.global.clearTimeout(this.backChannelTimerId_);\n this.backChannelTimerId_ = null;\n }\n\n this.clearDeadBackchannelTimer_();\n\n this.forwardChannelRequestPool_.cancel();\n\n if (this.forwardChannelTimerId_) {\n this.clearForwardChannelTimer_();\n }\n};\n\n\n/**\n * Clears the forward channel timer.\n * @private\n */\nWebChannelBase.prototype.clearForwardChannelTimer_ = function() {\n 'use strict';\n if (typeof this.forwardChannelTimerId_ === 'number') {\n goog.global.clearTimeout(this.forwardChannelTimerId_);\n }\n\n this.forwardChannelTimerId_ = null;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to all the requests sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getExtraHeaders = function() {\n 'use strict';\n return this.extraHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to the init requests\n * sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getInitHeaders = function() {\n 'use strict';\n return this.initHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to the init requests sent to the server.\n *\n * @param {Object} initHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setInitHeaders = function(initHeaders) {\n 'use strict';\n this.initHeaders_ = initHeaders;\n};\n\n\n/**\n * Sets the URL param name to overwrite custom HTTP headers.\n *\n * @param {string} httpHeadersOverwriteParam The URL param name.\n */\nWebChannelBase.prototype.setHttpHeadersOverwriteParam = function(\n httpHeadersOverwriteParam) {\n 'use strict';\n this.httpHeadersOverwriteParam_ = httpHeadersOverwriteParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionIdParam = function(httpSessionIdParam) {\n 'use strict';\n this.httpSessionIdParam_ = httpSessionIdParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionIdParam = function() {\n 'use strict';\n return this.httpSessionIdParam_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionId = function(httpSessionId) {\n 'use strict';\n this.httpSessionId_ = httpSessionId;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionId = function() {\n 'use strict';\n return this.httpSessionId_;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nWebChannelBase.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets whether cross origin requests are supported for the channel.\n *\n * Setting this allows the creation of requests to secondary domains and\n * sends XHRs with the CORS withCredentials bit set to true.\n *\n * In order for cross-origin requests to work, the server will also need to set\n * CORS response headers as per:\n * https://developer.mozilla.org/en-US/docs/HTTP_access_control\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported.\n */\nWebChannelBase.prototype.setSupportsCrossDomainXhrs = function(\n supportCrossDomain) {\n 'use strict';\n this.supportsCrossDomainXhrs_ = supportCrossDomain;\n};\n\n\n/**\n * Returns the handler used for channel callback events.\n *\n * @return {WebChannelBase.Handler} The handler.\n */\nWebChannelBase.prototype.getHandler = function() {\n 'use strict';\n return this.handler_;\n};\n\n\n/**\n * Sets the handler used for channel callback events.\n * @param {WebChannelBase.Handler} handler The handler to set.\n */\nWebChannelBase.prototype.setHandler = function(handler) {\n 'use strict';\n this.handler_ = handler;\n};\n\n\n/**\n * Returns whether the channel allows the use of a subdomain. There may be\n * cases where this isn't allowed.\n * @return {boolean} Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.getAllowHostPrefix = function() {\n 'use strict';\n return this.allowHostPrefix_;\n};\n\n\n/**\n * Sets whether the channel allows the use of a subdomain. There may be cases\n * where this isn't allowed, for example, logging in with troutboard where\n * using a subdomain causes Apache to force the user to authenticate twice.\n * @param {boolean} allowHostPrefix Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.setAllowHostPrefix = function(allowHostPrefix) {\n 'use strict';\n this.allowHostPrefix_ = allowHostPrefix;\n};\n\n\n/**\n * Returns whether the channel is buffered or not. This may be\n * queried in the WebChannelBase.okToMakeRequest() callback.\n *\n * @return {boolean} Whether the channel is buffered.\n */\nWebChannelBase.prototype.isBuffered = function() {\n 'use strict';\n return !this.enableStreaming_;\n};\n\n\n/**\n * Returns whether streaming mode is allowed. In certain debugging situations,\n * it's useful for the application to have a way to disable streaming mode for a\n * user.\n\n * @return {boolean} Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.getAllowStreamingMode = function() {\n 'use strict';\n return this.allowStreamingMode_;\n};\n\n\n/**\n * Sets whether streaming mode is allowed. In certain debugging situations, it's\n * useful for the application to have a way to disable streaming mode for a\n * user.\n * @param {boolean} allowStreamingMode Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.setAllowStreamingMode = function(allowStreamingMode) {\n 'use strict';\n this.allowStreamingMode_ = allowStreamingMode;\n};\n\n\n/**\n * Sends a request to the server. The format of the request is a Map data\n * structure of key/value pairs. These maps are then encoded in a format\n * suitable for the wire and then reconstituted as a Map data structure that\n * the server can process.\n * @param {!Object|!goog.collections.maps.MapLike} map The map to send.\n * @param {!Object=} opt_context The context associated with the map.\n */\nWebChannelBase.prototype.sendMap = function(map, opt_context) {\n 'use strict';\n goog.asserts.assert(\n this.state_ != WebChannelBase.State.CLOSED,\n 'Invalid operation: sending map when state is closed');\n\n // We can only send 1000 maps per POST, but typically we should never have\n // that much to send, so warn if we exceed that (we still send all the maps).\n if (this.outgoingMaps_.length == WebChannelBase.MAX_MAPS_PER_REQUEST_) {\n // severe() is temporary so that we get these uploaded and can figure out\n // what's causing them. Afterwards can change to warning().\n this.channelDebug_.severe(function() {\n 'use strict';\n return 'Already have ' + WebChannelBase.MAX_MAPS_PER_REQUEST_ +\n ' queued maps upon queueing ' + goog.json.serialize(map);\n });\n }\n\n this.outgoingMaps_.push(\n new Wire.QueuedMap(this.nextMapId_++, map, opt_context));\n\n // Messages need be buffered during OPENING to avoid server-side race\n if (this.state_ == WebChannelBase.State.OPENED) {\n this.ensureForwardChannel_();\n }\n};\n\n\n/**\n * When set to true, this changes the behavior of the forward channel so it\n * will not retry requests; it will fail after one network failure, and if\n * there was already one network failure, the request will fail immediately.\n * @param {boolean} failFast Whether or not to fail fast.\n */\nWebChannelBase.prototype.setFailFast = function(failFast) {\n 'use strict';\n this.failFast_ = failFast;\n this.channelDebug_.info('setFailFast: ' + failFast);\n if ((this.forwardChannelRequestPool_.hasPendingRequest() ||\n this.forwardChannelTimerId_) &&\n this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) {\n const self = this;\n this.channelDebug_.info(function() {\n 'use strict';\n return 'Retry count ' + self.forwardChannelRetryCount_ +\n ' > new maxRetries ' + self.getForwardChannelMaxRetries() +\n '. Fail immediately!';\n });\n\n if (!this.forwardChannelRequestPool_.forceComplete(\n goog.bind(this.onRequestComplete, this))) {\n // i.e., this.forwardChannelTimerId_\n this.clearForwardChannelTimer_();\n // The error code from the last failed request is gone, so just use a\n // generic one.\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n }\n }\n};\n\n\n/**\n * @return {number} The max number of forward-channel retries, which will be 0\n * in fail-fast mode.\n */\nWebChannelBase.prototype.getForwardChannelMaxRetries = function() {\n 'use strict';\n return this.failFast_ ? 0 : this.forwardChannelMaxRetries_;\n};\n\n\n/**\n * Sets the maximum number of attempts to connect to the server for forward\n * channel requests.\n * @param {number} retries The maximum number of attempts.\n */\nWebChannelBase.prototype.setForwardChannelMaxRetries = function(retries) {\n 'use strict';\n this.forwardChannelMaxRetries_ = retries;\n};\n\n\n/**\n * Sets the timeout for a forward channel request.\n * @param {number} timeoutMs The timeout in milliseconds.\n */\nWebChannelBase.prototype.setForwardChannelRequestTimeout = function(timeoutMs) {\n 'use strict';\n this.forwardChannelRequestTimeoutMs_ = timeoutMs;\n};\n\n\n/**\n * @return {number} The max number of back-channel retries, which is a constant.\n */\nWebChannelBase.prototype.getBackChannelMaxRetries = function() {\n 'use strict';\n // Back-channel retries is a constant.\n return WebChannelBase.BACK_CHANNEL_MAX_RETRIES;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isClosed = function() {\n 'use strict';\n return this.state_ == WebChannelBase.State.CLOSED;\n};\n\n\n/**\n * Returns the channel state.\n * @return {WebChannelBase.State} The current state of the channel.\n */\nWebChannelBase.prototype.getState = function() {\n 'use strict';\n return this.state_;\n};\n\n\n/**\n * @return {!Object<string, string>|undefined} The response headers received\n * along with the non-200 status.\n */\nWebChannelBase.prototype.getLastResponseHeaders = function() {\n 'use strict';\n return this.errorResponseHeaders_;\n};\n\n\n/**\n * @return {number} The non-200 status code received that causes the channel to\n * be aborted.\n */\nWebChannelBase.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.errorResponseStatusCode_;\n};\n\n\n/**\n * @return {number} The last array id received.\n */\nWebChannelBase.prototype.getLastArrayId = function() {\n 'use strict';\n return this.lastArrayId_;\n};\n\n\n/**\n * Returns whether there are outstanding requests servicing the channel.\n * @return {boolean} true if there are outstanding requests.\n */\nWebChannelBase.prototype.hasOutstandingRequests = function() {\n 'use strict';\n return this.getOutstandingRequests_() != 0;\n};\n\n\n/**\n * Returns the number of outstanding requests.\n * @return {number} The number of outstanding requests to the server.\n * @private\n */\nWebChannelBase.prototype.getOutstandingRequests_ = function() {\n 'use strict';\n let count = 0;\n if (this.backChannelRequest_) {\n count++;\n }\n count += this.forwardChannelRequestPool_.getRequestCount();\n return count;\n};\n\n\n/**\n * Ensures that a forward channel request is scheduled.\n * @private\n */\nWebChannelBase.prototype.ensureForwardChannel_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.isFull()) {\n // enough connection in process - no need to start a new request\n return;\n }\n\n if (this.forwardChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n this.forwardChannelTimerId_ = true;\n goog.async.run(this.onStartForwardChannelTimer_, this);\n\n this.forwardChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a forward-channel retry for the specified request, unless the max\n * retries has been reached.\n * @param {!ChannelRequest} request The failed request to retry.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryForwardChannel_ = function(request) {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() >=\n this.forwardChannelRequestPool_.getMaxSize() -\n (this.forwardChannelTimerId_ ? 1 : 0)) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Unexpected retry request is scheduled.');\n return false;\n }\n\n if (this.forwardChannelTimerId_) {\n this.channelDebug_.debug(\n 'Use the retry request that is already scheduled.');\n this.outgoingMaps_ =\n request.getPendingMessages().concat(this.outgoingMaps_);\n return true;\n }\n\n // No retry for open_() and fail-fast\n if (this.state_ == WebChannelBase.State.INIT ||\n this.state_ == WebChannelBase.State.OPENING ||\n (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry POST');\n\n this.forwardChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartForwardChannelTimer_, this, request),\n this.getRetryTime_(this.forwardChannelRetryCount_));\n this.forwardChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureForwardChannel\n * @param {ChannelRequest=} opt_retryRequest A failed request\n * to retry.\n * @private\n */\nWebChannelBase.prototype.onStartForwardChannelTimer_ = function(\n opt_retryRequest) {\n 'use strict';\n // null is possible if scheduled with async.run\n if (this.forwardChannelTimerId_) {\n this.forwardChannelTimerId_ = null;\n this.startForwardChannel_(opt_retryRequest);\n }\n};\n\n\n/**\n * Begins a new forward channel operation to the server.\n * @param {ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.startForwardChannel_ = function(opt_retryRequest) {\n 'use strict';\n this.channelDebug_.debug('startForwardChannel_');\n if (!this.okToMakeRequest_()) {\n return; // channel is cancelled\n } else if (this.state_ == WebChannelBase.State.INIT) {\n if (opt_retryRequest) {\n this.channelDebug_.severe('Not supposed to retry the open');\n return;\n }\n this.open_();\n this.state_ = WebChannelBase.State.OPENING;\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (opt_retryRequest) {\n this.makeForwardChannelRequest_(opt_retryRequest);\n return;\n }\n\n if (this.outgoingMaps_.length == 0) {\n this.channelDebug_.debug(\n 'startForwardChannel_ returned: ' +\n 'nothing to send');\n // no need to start a new forward channel request\n return;\n }\n\n if (this.forwardChannelRequestPool_.isFull()) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe(\n 'startForwardChannel_ returned: ' +\n 'connection already in progress');\n return;\n }\n\n this.makeForwardChannelRequest_();\n this.channelDebug_.debug('startForwardChannel_ finished, sent request');\n }\n};\n\n\n/**\n * Establishes a new channel session with the server.\n * @private\n */\nWebChannelBase.prototype.open_ = function() {\n 'use strict';\n this.channelDebug_.debug('open_()');\n this.nextRid_ = Math.floor(Math.random() * 100000);\n\n const rid = this.nextRid_++;\n const request =\n ChannelRequest.createChannelRequest(this, this.channelDebug_, '', rid);\n\n // mix the init headers\n let extraHeaders = this.extraHeaders_;\n if (this.initHeaders_) {\n if (extraHeaders) {\n extraHeaders = goog.object.clone(extraHeaders);\n goog.object.extend(extraHeaders, this.initHeaders_);\n } else {\n extraHeaders = this.initHeaders_;\n }\n }\n\n if (this.httpHeadersOverwriteParam_ === null &&\n !this.encodeInitMessageHeaders_) {\n request.setExtraHeaders(extraHeaders);\n extraHeaders = null;\n }\n\n let requestText = this.dequeueOutgoingMaps_(\n request,\n this.fastHandshake_ ? this.getMaxNumMessagesForFastHandshake_() :\n WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('RID', rid);\n\n if (this.clientVersion_ > 0) {\n uri.setParameterValue('CVER', this.clientVersion_);\n }\n\n // http-session-id to be generated as the response\n if (this.getHttpSessionIdParam()) {\n uri.setParameterValue(\n WebChannel.X_HTTP_SESSION_ID, this.getHttpSessionIdParam());\n }\n\n this.addAdditionalParams_(uri);\n\n if (extraHeaders) {\n if (this.encodeInitMessageHeaders_) {\n let encodedHeaders =\n httpCors.generateEncodedHttpHeadersOverwriteParam(extraHeaders);\n requestText = 'headers=' + encodedHeaders + '&' + requestText;\n } else if (this.httpHeadersOverwriteParam_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, extraHeaders);\n } // else - should not happen\n }\n\n this.forwardChannelRequestPool_.addRequest(request);\n\n if (this.blockingHandshake_) {\n uri.setParameterValue('TYPE', 'init'); // default to blocking in future\n }\n\n // Check the option and use GET to enable QUIC 0-RTT\n if (this.fastHandshake_) {\n uri.setParameterValue('$req', requestText);\n\n // enable handshake upgrade\n uri.setParameterValue('SID', 'null');\n request.setDecodeInitialResponse();\n\n request.xmlHttpPost(uri, null, true); // Send as a GET\n } else {\n request.xmlHttpPost(uri, requestText, true);\n }\n};\n\n\n/**\n * @return {number} The number of raw JSON messages to be encoded\n * with the fast-handshake (GET) request, including zero. If messages are not\n * encoded as raw JSON data, return WebChannelBase.MAX_MAPS_PER_REQUEST_\n * @private\n */\nWebChannelBase.prototype.getMaxNumMessagesForFastHandshake_ = function() {\n 'use strict';\n let total = 0;\n for (let i = 0; i < this.outgoingMaps_.length; i++) {\n const map = this.outgoingMaps_[i];\n const size = map.getRawDataSize();\n if (size === undefined) {\n break;\n }\n total += size;\n\n if (total > WebChannelBase.MAX_CHARS_PER_GET_) {\n return i;\n }\n\n if (total === WebChannelBase.MAX_CHARS_PER_GET_ ||\n i === this.outgoingMaps_.length - 1) {\n return i + 1;\n }\n }\n\n return WebChannelBase.MAX_MAPS_PER_REQUEST_;\n};\n\n\n\n/**\n * Makes a forward channel request using XMLHTTP.\n * @param {!ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.makeForwardChannelRequest_ = function(\n opt_retryRequest) {\n 'use strict';\n let rid;\n if (opt_retryRequest) {\n rid = opt_retryRequest.getRequestId(); // Reuse the same RID for a retry\n } else {\n rid = this.nextRid_++;\n }\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('AID', this.lastArrayId_);\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid,\n this.forwardChannelRetryCount_ + 1);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n request.setExtraHeaders(this.extraHeaders_);\n }\n\n let requestText;\n if (opt_retryRequest) {\n this.requeuePendingMaps_(opt_retryRequest);\n }\n requestText =\n this.dequeueOutgoingMaps_(request, WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n // Randomize from 50%-100% of the forward channel timeout to avoid\n // a big hit if servers happen to die at once.\n request.setTimeout(\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) +\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random()));\n this.forwardChannelRequestPool_.addRequest(request);\n request.xmlHttpPost(uri, requestText, true);\n};\n\n\n/**\n * Adds additional query parameters from `extraParams_` and `handler_` to the\n * given URI.\n * @param {!goog.Uri} uri The URI to add the parameters to.\n * @private\n */\nWebChannelBase.prototype.addAdditionalParams_ = function(uri) {\n 'use strict';\n if (this.extraParams_) {\n goog.object.forEach(this.extraParams_, function(value, key) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n\n if (this.handler_) {\n const params = this.handler_.getAdditionalParams(this);\n if (params) {\n goog.structs.forEach(params, function(value, key, coll) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n }\n};\n\n\n/**\n * Returns the request text from the outgoing maps and resets it.\n * @param {!ChannelRequest} request The new request for sending the messages.\n * @param {number} maxNum The maximum number of messages to be encoded\n * @return {string} The encoded request text created from all the currently\n * queued outgoing maps.\n * @private\n */\nWebChannelBase.prototype.dequeueOutgoingMaps_ = function(request, maxNum) {\n 'use strict';\n const count = Math.min(this.outgoingMaps_.length, maxNum);\n\n const badMapHandler = this.handler_ ?\n goog.bind(this.handler_.badMapError, this.handler_, this) :\n null;\n const result = this.wireCodec_.encodeMessageQueue(\n this.outgoingMaps_, count, badMapHandler);\n\n request.setPendingMessages(this.outgoingMaps_.splice(0, count));\n\n return result;\n};\n\n\n/**\n * Requeues unacknowledged sent arrays for retransmission in the next forward\n * channel request.\n * @param {!ChannelRequest} retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.requeuePendingMaps_ = function(retryRequest) {\n 'use strict';\n this.outgoingMaps_ =\n retryRequest.getPendingMessages().concat(this.outgoingMaps_);\n};\n\n\n/**\n * Ensures there is a backchannel request for receiving data from the server.\n * @private\n */\nWebChannelBase.prototype.ensureBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n // already have one\n return;\n }\n\n if (this.backChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n this.backChannelAttemptId_ = 1;\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n // backChannelTimerId_ stays unset, as with setTimeout(0)\n goog.async.run(this.onStartBackChannelTimer_, this);\n\n this.backChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a back-channel retry, unless the max retries has been reached.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_ || this.backChannelTimerId_) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Request already in progress');\n return false;\n }\n\n if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry GET');\n\n this.backChannelAttemptId_++;\n this.backChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartBackChannelTimer_, this),\n this.getRetryTime_(this.backChannelRetryCount_));\n this.backChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureBackChannel_.\n * @private\n */\nWebChannelBase.prototype.onStartBackChannelTimer_ = function() {\n 'use strict';\n this.backChannelTimerId_ = null;\n this.startBackChannel_();\n\n if (!this.detectBufferingProxy_) {\n return;\n }\n\n if (this.bpDetectionDone_) {\n return;\n }\n\n if (this.backChannelRequest_ == null || this.handshakeRttMs_ <= 0) {\n this.channelDebug_.warning(\n 'Skip bpDetectionTimerId_ ' + this.backChannelRequest_ + ' ' +\n this.handshakeRttMs_);\n return;\n }\n\n // This goes with each new request until bpDetectionDone_\n const bpDetectionTimeout = 2 * this.handshakeRttMs_;\n this.channelDebug_.info('BP detection timer enabled: ' + bpDetectionTimeout);\n\n this.bpDetectionTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBpDetectionTimer_, this), bpDetectionTimeout);\n};\n\n\n/**\n * Timer callback for bpDetection.\n * @private\n */\nWebChannelBase.prototype.onBpDetectionTimer_ = function() {\n 'use strict';\n if (!this.bpDetectionTimerId_) {\n this.channelDebug_.warning('Invalid operation.');\n return;\n }\n\n this.bpDetectionTimerId_ = null;\n this.channelDebug_.info('BP detection timeout reached.');\n\n goog.asserts.assert(\n this.backChannelRequest_ != null,\n 'Invalid state: no backchannel request');\n\n // We wait for extra response payload in addition to just headers to\n // cancel the timer.\n if (this.backChannelRequest_.getXhr() != null) {\n const responseData = this.backChannelRequest_.getXhr().getResponseText();\n if (responseData) {\n this.channelDebug_.warning(\n 'Timer should have been cancelled : ' + responseData);\n }\n }\n\n // Enable long-polling\n this.channelDebug_.info(\n 'Buffering proxy detected and switch to long-polling!');\n this.enableStreaming_ = false;\n\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\n\n // Cancel the request and start a new one immediately\n this.cancelBackChannelRequest_();\n this.startBackChannel_();\n};\n\n\n/**\n * Clears the timer for BP detection.\n * @private\n */\nWebChannelBase.prototype.clearBpDetectionTimer_ = function() {\n 'use strict';\n if (this.bpDetectionTimerId_ != null) {\n this.channelDebug_.debug('Cancel the BP detection timer.');\n goog.global.clearTimeout(this.bpDetectionTimerId_);\n this.bpDetectionTimerId_ = null;\n }\n};\n\n\n/**\n * Begins a new back channel operation to the server.\n * @private\n */\nWebChannelBase.prototype.startBackChannel_ = function() {\n 'use strict';\n if (!this.okToMakeRequest_()) {\n // channel is cancelled\n return;\n }\n\n this.channelDebug_.debug('Creating new HttpRequest');\n this.backChannelRequest_ = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n this.backChannelRequest_.setExtraHeaders(this.extraHeaders_);\n }\n\n this.backChannelRequest_.setReadyStateChangeThrottle(\n this.readyStateChangeThrottleMs_);\n const uri = this.backChannelUri_.clone();\n uri.setParameterValue('RID', 'rpc');\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('AID', this.lastArrayId_);\n\n uri.setParameterValue('CI', this.enableStreaming_ ? '0' : '1');\n if (!this.enableStreaming_ && this.longPollingTimeout_) {\n uri.setParameterValue('TO', this.longPollingTimeout_);\n }\n\n uri.setParameterValue('TYPE', 'xmlhttp');\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n if (this.backChannelRequestTimeoutMs_) {\n this.backChannelRequest_.setTimeout(this.backChannelRequestTimeoutMs_);\n }\n\n this.backChannelRequest_.xmlHttpGet(\n uri, true /* decodeChunks */, this.hostPrefix_);\n\n this.channelDebug_.debug('New Request created');\n};\n\n\n/**\n * Gives the handler a chance to return an error code and stop channel\n * execution. A handler might want to do this to check that the user is still\n * logged in, for example.\n * @private\n * @return {boolean} If it's OK to make a request.\n */\nWebChannelBase.prototype.okToMakeRequest_ = function() {\n 'use strict';\n if (this.handler_) {\n const result = this.handler_.okToMakeRequest(this);\n if (result != WebChannelBase.Error.OK) {\n this.channelDebug_.debug(\n 'Handler returned error code from okToMakeRequest');\n this.signalError_(result);\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onFirstByteReceived = function(request, responseText) {\n 'use strict';\n if (this.backChannelRequest_ == request && this.detectBufferingProxy_) {\n if (!this.bpDetectionDone_) {\n this.channelDebug_.info(\n 'Great, no buffering proxy detected. Bytes received: ' +\n responseText.length);\n goog.asserts.assert(\n this.bpDetectionTimerId_, 'Timer should not have been cancelled.');\n this.clearBpDetectionTimer_();\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\n }\n }\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onRequestData = function(request, responseText) {\n 'use strict';\n if (this.state_ == WebChannelBase.State.CLOSED ||\n (this.backChannelRequest_ != request &&\n !this.forwardChannelRequestPool_.hasRequest(request))) {\n // either CLOSED or a request we don't know about (perhaps an old request)\n return;\n }\n\n // first to check if request has been upgraded to backchannel\n if (!request.isInitialResponseDecoded() &&\n this.forwardChannelRequestPool_.hasRequest(request) &&\n this.state_ == WebChannelBase.State.OPENED) {\n let response;\n try {\n response = this.wireCodec_.decodeMessage(responseText);\n } catch (ex) {\n response = null;\n }\n if (Array.isArray(response) && response.length == 3) {\n this.handlePostResponse_(/** @type {!Array<?>} */ (response), request);\n this.onForwardChannelFlushed_();\n } else {\n this.channelDebug_.debug('Bad POST response data returned');\n this.signalError_(WebChannelBase.Error.BAD_RESPONSE);\n }\n } else {\n if (request.isInitialResponseDecoded() ||\n this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n }\n\n if (!goog.string.isEmptyOrWhitespace(responseText)) {\n let response = this.wireCodec_.decodeMessage(responseText);\n this.onInput_(/** @type {!Array<?>} */ (response), request);\n }\n }\n};\n\n\n/**\n * Checks if we need call the flush callback.\n *\n * @private\n */\nWebChannelBase.prototype.onForwardChannelFlushed_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() <= 1) {\n if (this.forwardChannelFlushedCallback_) {\n try {\n this.forwardChannelFlushedCallback_();\n } catch (ex) {\n this.channelDebug_.dumpException(\n ex, 'Exception from forwardChannelFlushedCallback_ ');\n }\n // reset\n this.forwardChannelFlushedCallback_ = undefined;\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server.\n * @param {Array<number>} responseValues The key value pairs in\n * the POST response.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n */\nWebChannelBase.prototype.handlePostResponse_ = function(\n responseValues, forwardReq) {\n 'use strict';\n // The first response value is set to 0 if server is missing backchannel.\n if (responseValues[0] == 0) {\n this.handleBackchannelMissing_(forwardReq);\n return;\n }\n this.lastPostResponseArrayId_ = responseValues[1];\n const outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_;\n if (0 < outstandingArrays) {\n const numOutstandingBackchannelBytes = responseValues[2];\n this.channelDebug_.debug(\n numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays +\n ' arrays) are outstanding on the BackChannel');\n if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) {\n return;\n }\n if (!this.deadBackChannelTimerId_) {\n // We expect to receive data within 2 RTTs or we retry the backchannel.\n this.deadBackChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBackChannelDead_, this),\n 2 * WebChannelBase.RTT_ESTIMATE);\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server telling us that it has detected that\n * we have no hanging GET connection.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.handleBackchannelMissing_ = function(forwardReq) {\n 'use strict';\n // As long as the back channel was started before the POST was sent,\n // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE\n // so as not to excessively retry the backchannel\n this.channelDebug_.debug('Server claims our backchannel is missing.');\n if (this.backChannelTimerId_) {\n this.channelDebug_.debug('But we are currently starting the request.');\n return;\n } else if (!this.backChannelRequest_) {\n this.channelDebug_.warning('We do not have a BackChannel established');\n } else if (\n this.backChannelRequest_.getRequestStartTime() +\n WebChannelBase.RTT_ESTIMATE <\n forwardReq.getRequestStartTime()) {\n this.clearDeadBackchannelTimer_();\n this.cancelBackChannelRequest_();\n } else {\n return;\n }\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_MISSING);\n};\n\n\n/**\n * Determines whether we should start the process of retrying a possibly\n * dead backchannel.\n * @param {number} outstandingBytes The number of bytes for which the server has\n * not yet received acknowledgement.\n * @return {boolean} Whether to start the backchannel retry timer.\n * @private\n */\nWebChannelBase.prototype.shouldRetryBackChannel_ = function(outstandingBytes) {\n 'use strict';\n // Not too many outstanding bytes, not buffered and not after a retry.\n return outstandingBytes <\n WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF &&\n !this.isBuffered() && this.backChannelRetryCount_ == 0;\n};\n\n\n/**\n * Decides which host prefix should be used, if any. If there is a handler,\n * allows the handler to validate a host prefix provided by the server, and\n * optionally override it.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix to actually use, if any. Will return null\n * if the use of host prefixes was disabled via setAllowHostPrefix().\n * @override\n */\nWebChannelBase.prototype.correctHostPrefix = function(serverHostPrefix) {\n 'use strict';\n if (this.allowHostPrefix_) {\n if (this.handler_) {\n return this.handler_.correctHostPrefix(serverHostPrefix);\n }\n return serverHostPrefix;\n }\n return null;\n};\n\n\n/**\n * Handles the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.onBackChannelDead_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n this.deadBackChannelTimerId_ = null;\n this.cancelBackChannelRequest_();\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_DEAD);\n }\n};\n\n\n/**\n * Clears the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.clearDeadBackchannelTimer_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n goog.global.clearTimeout(this.deadBackChannelTimerId_);\n this.deadBackChannelTimerId_ = null;\n }\n};\n\n\n/**\n * Returns whether or not the given error/status combination is fatal or not.\n * On fatal errors we immediately close the session rather than retrying the\n * failed request.\n * @param {?ChannelRequest.Error} error The error code for the\n * failed request.\n * @param {number} statusCode The last HTTP status code.\n * @return {boolean} Whether or not the error is fatal.\n * @private\n */\nWebChannelBase.isFatalError_ = function(error, statusCode) {\n 'use strict';\n return error == ChannelRequest.Error.UNKNOWN_SESSION_ID ||\n (error == ChannelRequest.Error.STATUS && statusCode > 0);\n};\n\n\n/**\n * @override\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.onRequestComplete = function(request) {\n 'use strict';\n this.channelDebug_.debug('Request complete');\n let type;\n let pendingMessages = null;\n if (this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n this.clearBpDetectionTimer_();\n this.backChannelRequest_ = null;\n type = WebChannelBase.ChannelType_.BACK_CHANNEL;\n } else if (this.forwardChannelRequestPool_.hasRequest(request)) {\n pendingMessages = request.getPendingMessages();\n this.forwardChannelRequestPool_.removeRequest(request);\n type = WebChannelBase.ChannelType_.FORWARD_CHANNEL;\n } else {\n // return if it was an old request from a previous session\n return;\n }\n\n if (this.state_ == WebChannelBase.State.CLOSED) {\n return;\n }\n\n if (request.getSuccess()) {\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n const size = request.getPostData() ? request.getPostData().length : 0;\n requestStats.notifyTimingEvent(\n size, Date.now() - request.getRequestStartTime(),\n this.forwardChannelRetryCount_);\n this.ensureForwardChannel_();\n this.onSuccess_(request);\n } else { // i.e., back-channel\n this.ensureBackChannel_();\n }\n return;\n }\n // Else unsuccessful. Fall through.\n\n const lastStatusCode = request.getLastStatusCode();\n const lastError = request.getLastError();\n if (!WebChannelBase.isFatalError_(lastError, lastStatusCode)) {\n // Maybe retry.\n const self = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'Maybe retrying, last error: ' +\n ChannelRequest.errorStringFromCode(\n lastError, self.errorResponseStatusCode_);\n });\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n if (this.maybeRetryForwardChannel_(request)) {\n return;\n }\n }\n if (type == WebChannelBase.ChannelType_.BACK_CHANNEL) {\n if (this.maybeRetryBackChannel_()) {\n return;\n }\n }\n // Else exceeded max retries. Fall through.\n this.channelDebug_.debug('Exceeded max number of retries');\n } else {\n // Else fatal error. Fall through and mark the pending maps as failed.\n this.channelDebug_.debug('Not retrying due to error type');\n\n if (lastStatusCode > 200) {\n this.errorResponseStatusCode_ = request.getLastStatusCode();\n this.errorResponseHeaders_ = request.getErrorResponseHeaders();\n }\n }\n\n // Abort the channel now\n\n // Record pending messages from the failed request\n if (pendingMessages && pendingMessages.length > 0) {\n this.forwardChannelRequestPool_.addPendingMessages(pendingMessages);\n }\n\n this.channelDebug_.debug('Error: HTTP request failed');\n switch (lastError) {\n case ChannelRequest.Error.NO_DATA:\n this.signalError_(WebChannelBase.Error.NO_DATA);\n break;\n case ChannelRequest.Error.BAD_DATA:\n this.signalError_(WebChannelBase.Error.BAD_DATA);\n break;\n case ChannelRequest.Error.UNKNOWN_SESSION_ID:\n this.signalError_(WebChannelBase.Error.UNKNOWN_SESSION_ID);\n break;\n default:\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n break;\n }\n};\n\n\n/**\n * @param {number} retryCount Number of retries so far.\n * @return {number} Time in ms before firing next retry request.\n * @private\n */\nWebChannelBase.prototype.getRetryTime_ = function(retryCount) {\n 'use strict';\n let retryTime = this.baseRetryDelayMs_ +\n Math.floor(Math.random() * this.retryDelaySeedMs_);\n if (!this.isActive()) {\n this.channelDebug_.debug('Inactive channel');\n retryTime = retryTime * WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR;\n }\n // Backoff for subsequent retries\n retryTime *= retryCount;\n return retryTime;\n};\n\n\n/**\n * @param {number} baseDelayMs The base part of the retry delay, in ms.\n * @param {number} delaySeedMs A random delay between 0 and this is added to\n * the base part.\n */\nWebChannelBase.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) {\n 'use strict';\n this.baseRetryDelayMs_ = baseDelayMs;\n this.retryDelaySeedMs_ = delaySeedMs;\n};\n\n\n/**\n * Apply any handshake control headers.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.applyControlHeaders_ = function(request) {\n 'use strict';\n const xhr = request.getXhr();\n if (xhr) {\n const clientProtocol =\n xhr.getStreamingResponseHeader(WebChannel.X_CLIENT_WIRE_PROTOCOL);\n if (clientProtocol) {\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\n }\n\n if (this.getHttpSessionIdParam()) {\n const httpSessionIdHeader =\n xhr.getStreamingResponseHeader(WebChannel.X_HTTP_SESSION_ID);\n if (httpSessionIdHeader) {\n this.setHttpSessionId(httpSessionIdHeader);\n // update the cached uri\n const httpSessionIdParam = this.getHttpSessionIdParam();\n\n this.forwardChannelUri_.setParameterValue(\n /** @type {string} */ (httpSessionIdParam), // never null\n httpSessionIdHeader);\n } else {\n this.channelDebug_.warning(\n 'Missing X_HTTP_SESSION_ID in the handshake response');\n }\n }\n }\n};\n\n\n/**\n * Processes the data returned by the server.\n * @param {!Array<!Array<?>>} respArray The response array returned\n * by the server.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n * @suppress {strictPrimitiveOperators}\n */\nWebChannelBase.prototype.onInput_ = function(respArray, request) {\n 'use strict';\n const batch =\n this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null;\n for (let i = 0; i < respArray.length; i++) {\n let nextArray = respArray[i];\n this.lastArrayId_ = nextArray[0];\n nextArray = nextArray[1];\n if (this.state_ == WebChannelBase.State.OPENING) {\n if (nextArray[0] == 'c') {\n this.sid_ = nextArray[1];\n this.hostPrefix_ = this.correctHostPrefix(nextArray[2]);\n\n const negotiatedVersion = nextArray[3];\n if (negotiatedVersion != null) {\n this.channelVersion_ = negotiatedVersion;\n this.channelDebug_.info('VER=' + this.channelVersion_);\n }\n\n const negotiatedServerVersion = nextArray[4];\n if (negotiatedServerVersion != null) {\n this.serverVersion_ = negotiatedServerVersion;\n this.channelDebug_.info('SVER=' + this.serverVersion_);\n }\n\n // CVER=22\n const serverKeepaliveMs = nextArray[5];\n if (serverKeepaliveMs != null &&\n typeof serverKeepaliveMs === 'number' && serverKeepaliveMs > 0) {\n const timeout = 1.5 * serverKeepaliveMs;\n this.backChannelRequestTimeoutMs_ = timeout;\n this.channelDebug_.info('backChannelRequestTimeoutMs_=' + timeout);\n }\n\n this.applyControlHeaders_(request);\n\n this.state_ = WebChannelBase.State.OPENED;\n if (this.handler_) {\n this.handler_.channelOpened(this);\n }\n\n if (this.detectBufferingProxy_) {\n this.handshakeRttMs_ = Date.now() - request.getRequestStartTime();\n this.channelDebug_.info(\n 'Handshake RTT: ' + this.handshakeRttMs_ + 'ms');\n }\n\n this.startBackchannelAfterHandshake_(request);\n\n if (this.outgoingMaps_.length > 0) {\n this.ensureForwardChannel_();\n }\n } else if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n // treat close also as an abort\n this.signalError_(WebChannelBase.Error.STOP);\n }\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n batch.length = 0;\n }\n if (nextArray[0] == 'stop') {\n this.signalError_(WebChannelBase.Error.STOP);\n } else {\n this.disconnect();\n }\n } else if (nextArray[0] == 'noop') {\n // ignore - noop to keep connection happy\n } else {\n if (batch) {\n batch.push(nextArray);\n } else if (this.handler_) {\n this.handler_.channelHandleArray(this, nextArray);\n }\n }\n // We have received useful data on the back-channel, so clear its retry\n // count. We do this because back-channels by design do not complete\n // quickly, so on a flaky connection we could have many fail to complete\n // fully but still deliver a lot of data before they fail. We don't want\n // to count such failures towards the retry limit, because we don't want\n // to give up on a session if we can still receive data.\n this.backChannelRetryCount_ = 0;\n }\n }\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n }\n};\n\n\n/**\n * Starts the backchannel after the handshake.\n *\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.startBackchannelAfterHandshake_ = function(request) {\n 'use strict';\n this.backChannelUri_ = this.getBackChannelUri(\n this.hostPrefix_, /** @type {string} */ (this.path_));\n\n if (request.isInitialResponseDecoded()) {\n this.channelDebug_.debug('Upgrade the handshake request to a backchannel.');\n this.forwardChannelRequestPool_.removeRequest(request);\n request.resetTimeout(this.backChannelRequestTimeoutMs_);\n this.backChannelRequest_ = request;\n } else {\n this.ensureBackChannel_();\n }\n};\n\n\n/**\n * Helper to ensure the channel is in the expected state.\n * @param {...number} var_args The channel must be in one of the indicated\n * states.\n * @private\n */\nWebChannelBase.prototype.ensureInState_ = function(var_args) {\n 'use strict';\n goog.asserts.assert(\n goog.array.contains(arguments, this.state_),\n 'Unexpected channel state: %s', this.state_);\n};\n\n\n/**\n * Signals an error has occurred.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.signalError_ = function(error) {\n 'use strict';\n this.channelDebug_.info('Error code ' + error);\n if (error == WebChannelBase.Error.REQUEST_FAILED) {\n if (ENABLE_GOOGLE_COM_PING) {\n // Create a separate Internet connection to check\n // if it's a server error or user's network error.\n let imageUri = null;\n if (this.handler_) {\n imageUri = this.handler_.getNetworkTestImageUri(this);\n }\n netUtils.testNetwork(\n goog.bind(this.testNetworkCallback_, this), imageUri);\n }\n } else {\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n }\n this.onError_(error);\n};\n\n\n/**\n * Callback for netUtils.testNetwork during error handling.\n * @param {boolean} networkUp Whether the network is up.\n * @private\n */\nWebChannelBase.prototype.testNetworkCallback_ = function(networkUp) {\n 'use strict';\n if (networkUp) {\n this.channelDebug_.info('Successfully pinged google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n } else {\n this.channelDebug_.info('Failed to ping google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_NETWORK);\n // Do not call onError_ again to eliminate duplicated Error events.\n }\n};\n\n\n/**\n * Called when messages have been successfully sent from the queue.\n * @param {!ChannelRequest} request The request object\n * @private\n */\nWebChannelBase.prototype.onSuccess_ = function(request) {\n 'use strict';\n if (this.handler_) {\n this.handler_.channelSuccess(this, request);\n }\n};\n\n\n/**\n * Called when we've determined the final error for a channel. It closes the\n * notifiers the handler of the error and closes the channel.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.onError_ = function(error) {\n 'use strict';\n this.channelDebug_.debug('HttpChannel: error - ' + error);\n this.state_ = WebChannelBase.State.CLOSED;\n if (this.handler_) {\n this.handler_.channelError(this, error);\n }\n this.onClose_();\n this.cancelRequests_();\n};\n\n\n/**\n * Called when the channel has been closed. It notifiers the handler of the\n * event, and reports any pending or undelivered maps.\n * @private\n */\nWebChannelBase.prototype.onClose_ = function() {\n 'use strict';\n this.state_ = WebChannelBase.State.CLOSED;\n this.nonAckedMapsAtChannelClose_ = [];\n if (this.handler_) {\n const pendingMessages =\n this.forwardChannelRequestPool_.getPendingMessages();\n\n if (pendingMessages.length == 0 && this.outgoingMaps_.length == 0) {\n this.handler_.channelClosed(this);\n } else {\n this.channelDebug_.debug(\n () => 'Number of undelivered maps' +\n ', pending: ' + pendingMessages.length +\n ', outgoing: ' + this.outgoingMaps_.length);\n\n goog.array.extend(this.nonAckedMapsAtChannelClose_, pendingMessages);\n goog.array.extend(this.nonAckedMapsAtChannelClose_, this.outgoingMaps_);\n\n this.forwardChannelRequestPool_.clearPendingMessages();\n\n const copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_);\n this.outgoingMaps_.length = 0;\n\n this.handler_.channelClosed(this, pendingMessages, copyOfUndeliveredMaps);\n }\n }\n};\n\n/**\n * @return {!Array<!Wire.QueuedMap>} Returns the list of non-acked maps, both\n * during an active channel or after the channel is closed. Refer to the\n * `getNonAckedMessages()` API for definitions of non-acked messages.\n */\nWebChannelBase.prototype.getNonAckedMaps = function() {\n if (this.state_ == WebChannelBase.State.CLOSED) {\n goog.asserts.assert(\n this.nonAckedMapsAtChannelClose_ != null,\n 'nonAckedMapsAtChannelClose_ is not set after channel close.');\n return this.nonAckedMapsAtChannelClose_;\n }\n\n // The underlying message objects are not cloned and thus exposes a mutability\n // risk, but is chosen to make strict equality (i.e. ===) checks possible for\n // callers.\n let unAckedMaps = [];\n goog.array.extend(\n unAckedMaps, this.forwardChannelRequestPool_.getPendingMessages());\n goog.array.extend(unAckedMaps, this.outgoingMaps_);\n\n return unAckedMaps;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getForwardChannelUri = function(path) {\n 'use strict';\n const uri = this.createDataUri(null, path);\n this.channelDebug_.debug('GetForwardChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getConnectionState = function() {\n 'use strict';\n return this.connState_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getBackChannelUri = function(hostPrefix, path) {\n 'use strict';\n const uri = this.createDataUri(\n this.shouldUseSecondaryDomains() ? hostPrefix : null, path);\n this.channelDebug_.debug('GetBackChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.createDataUri = function(\n hostPrefix, path, opt_overridePort) {\n 'use strict';\n let uri = goog.Uri.parse(path);\n const uriAbsolute = (uri.getDomain() != '');\n if (uriAbsolute) {\n if (hostPrefix) {\n uri.setDomain(hostPrefix + '.' + uri.getDomain());\n }\n\n uri.setPort(opt_overridePort || uri.getPort());\n } else {\n const locationPage = goog.global.location;\n let hostName;\n if (hostPrefix) {\n hostName = hostPrefix + '.' + locationPage.hostname;\n } else {\n hostName = locationPage.hostname;\n }\n\n const port = opt_overridePort || +locationPage.port;\n\n uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path);\n }\n\n const param = this.getHttpSessionIdParam();\n const value = this.getHttpSessionId();\n if (param && value) {\n uri.setParameterValue(param, value);\n }\n\n // Add the protocol version to the URI.\n uri.setParameterValue('VER', this.channelVersion_);\n\n this.addAdditionalParams_(uri);\n\n return uri;\n};\n\n/**\n * @override\n * @param {?string} hostPrefix The host prefix, if we need an XhrIo object\n * capable of calling a secondary domain.\n * @param {boolean=} isStreaming Whether or not fetch/streams are enabled for\n * the underlying HTTP request.\n * @return {!goog.net.XhrIo} A new XhrIo object.\n */\nWebChannelBase.prototype.createXhrIo = function(hostPrefix, isStreaming) {\n 'use strict';\n if (hostPrefix && !this.supportsCrossDomainXhrs_) {\n throw new Error('Can\\'t create secondary domain capable XhrIo object.');\n }\n let xhr;\n if (this.usesFetchStreams_ && !this.xmlHttpFactory_) {\n xhr = new goog.net.XhrIo(\n new goog.net.FetchXmlHttpFactory({streamBinaryChunks: isStreaming}));\n } else {\n xhr = new goog.net.XhrIo(this.xmlHttpFactory_);\n }\n xhr.setWithCredentials(this.supportsCrossDomainXhrs_);\n return xhr;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isActive = function() {\n 'use strict';\n return !!this.handler_ && this.handler_.isActive(this);\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.shouldUseSecondaryDomains = function() {\n 'use strict';\n return this.supportsCrossDomainXhrs_;\n};\n\n\n/**\n * Sets (overwrites) the forward channel flush callback.\n *\n * @param {function()} callback The callback to be invoked.\n */\nWebChannelBase.prototype.setForwardChannelFlushCallback = function(callback) {\n 'use strict';\n this.forwardChannelFlushedCallback_ = callback;\n};\n\n\n/**\n * Abstract base class for the channel handler\n * @constructor\n * @struct\n */\nWebChannelBase.Handler = function() {};\n\n\n/**\n * Callback handler for when a batch of response arrays is received from the\n * server. When null, batched dispatching is disabled.\n * @type {?function(!WebChannelBase, !Array<!Array<?>>)}\n */\nWebChannelBase.Handler.prototype.channelHandleMultipleArrays = null;\n\n\n/**\n * Whether it's okay to make a request to the server. A handler can return\n * false if the channel should fail. For example, if the user has logged out,\n * the handler may want all requests to fail immediately.\n * @param {WebChannelBase} channel The channel.\n * @return {WebChannelBase.Error} An error code. The code should\n * return WebChannelBase.Error.OK to indicate it's okay. Any other\n * error code will cause a failure.\n */\nWebChannelBase.Handler.prototype.okToMakeRequest = function(channel) {\n 'use strict';\n return WebChannelBase.Error.OK;\n};\n\n\n/**\n * Indicates the WebChannel has successfully negotiated with the server\n * and can now send and receive data.\n * @param {WebChannelBase} channel The channel.\n */\nWebChannelBase.Handler.prototype.channelOpened = function(channel) {};\n\n\n/**\n * New input is available for the application to process.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {!Array<?>|!Object} array The data array.\n */\nWebChannelBase.Handler.prototype.channelHandleArray = function(\n channel, array) {};\n\n\n/**\n * Indicates messages that have been successfully sent on the channel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {!ChannelRequest} request The request object that contains\n * the pending messages that have been successfully delivered to the server.\n */\nWebChannelBase.Handler.prototype.channelSuccess = function(channel, request) {};\n\n\n/**\n * Indicates an error occurred on the WebChannel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {WebChannelBase.Error} error The error code.\n */\nWebChannelBase.Handler.prototype.channelError = function(channel, error) {};\n\n\n/**\n * Indicates the WebChannel is closed. Also notifies about which maps,\n * if any, that may not have been delivered to the server.\n * @param {WebChannelBase} channel The channel.\n * @param {Array<Wire.QueuedMap>=} opt_pendingMaps The\n * array of pending maps, which may or may not have been delivered to the\n * server.\n * @param {Array<Wire.QueuedMap>=} opt_undeliveredMaps\n * The array of undelivered maps, which have definitely not been delivered\n * to the server.\n */\nWebChannelBase.Handler.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {};\n\n\n/**\n * Gets any parameters that should be added at the time another connection is\n * made to the server.\n * @param {WebChannelBase} channel The channel.\n * @return {!Object} Extra parameter keys and values to add to the requests.\n */\nWebChannelBase.Handler.prototype.getAdditionalParams = function(channel) {\n 'use strict';\n return {};\n};\n\n\n/**\n * Gets the URI of an image that can be used to test network connectivity.\n * @param {WebChannelBase} channel The channel.\n * @return {goog.Uri?} A custom URI to load for the network test.\n */\nWebChannelBase.Handler.prototype.getNetworkTestImageUri = function(channel) {\n 'use strict';\n return null;\n};\n\n\n/**\n * Gets whether this channel is currently active. This is used to determine the\n * length of time to wait before retrying.\n * @param {WebChannelBase} channel The channel.\n * @return {boolean} Whether the channel is currently active.\n */\nWebChannelBase.Handler.prototype.isActive = function(channel) {\n 'use strict';\n return true;\n};\n\n/**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @override\n * @return {boolean}\n */\nWebChannelBase.prototype.usesFetchStreams = function() {\n 'use strict';\n return this.usesFetchStreams_;\n};\n\n\n/**\n * Called by the channel if enumeration of the map throws an exception.\n * @param {WebChannelBase} channel The channel.\n * @param {Object} map The map that can't be enumerated.\n */\nWebChannelBase.Handler.prototype.badMapError = function(channel, map) {};\n\n\n/**\n * Allows the handler to override a host prefix provided by the server. Will\n * be called whenever the channel has received such a prefix and is considering\n * its use.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix the client should use.\n */\nWebChannelBase.Handler.prototype.correctHostPrefix = function(\n serverHostPrefix) {\n 'use strict';\n return serverHostPrefix;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class for parsing and formatting URIs.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to\n * create a new instance of the goog.Uri object from Uri parts.\n *\n * e.g: <code>var myUri = new goog.Uri(window.location);</code>\n *\n * Implements RFC 3986 for parsing/formatting URIs.\n * http://www.ietf.org/rfc/rfc3986.txt\n *\n * Some changes have been made to the interface (more like .NETs), though the\n * internal representation is now of un-encoded parts, this will change the\n * behavior slightly.\n */\n\ngoog.provide('goog.Uri');\ngoog.provide('goog.Uri.QueryData');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.string');\ngoog.require('goog.structs');\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 'use strict';\n /**\n * Scheme such as \"http\".\n * @private {string}\n */\n this.scheme_ = '';\n\n /**\n * User credentials in the form \"username:password\".\n * @private {string}\n */\n this.userInfo_ = '';\n\n /**\n * Domain part, e.g. \"www.google.com\".\n * @private {string}\n */\n this.domain_ = '';\n\n /**\n * Port, e.g. 8080.\n * @private {?number}\n */\n this.port_ = null;\n\n /**\n * Path, e.g. \"/tests/img.png\".\n * @private {string}\n */\n this.path_ = '';\n\n /**\n * The fragment without the #.\n * @private {string}\n */\n this.fragment_ = '';\n\n /**\n * Whether or not this Uri should be treated as Read Only.\n * @private {boolean}\n */\n this.isReadOnly_ = false;\n\n /**\n * Whether or not to ignore case when comparing query params.\n * @private {boolean}\n */\n this.ignoreCase_ = false;\n\n /**\n * Object representing query data.\n * @private {!goog.Uri.QueryData}\n */\n this.queryData_;\n\n // Parse in the uri string\n var m;\n if (opt_uri instanceof goog.Uri) {\n this.ignoreCase_ = (opt_ignoreCase !== undefined) ? opt_ignoreCase :\n opt_uri.getIgnoreCase();\n this.setScheme(opt_uri.getScheme());\n this.setUserInfo(opt_uri.getUserInfo());\n this.setDomain(opt_uri.getDomain());\n this.setPort(opt_uri.getPort());\n this.setPath(opt_uri.getPath());\n this.setQueryData(opt_uri.getQueryData().clone());\n this.setFragment(opt_uri.getFragment());\n } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {\n this.ignoreCase_ = !!opt_ignoreCase;\n\n // Set the parts -- decoding as we do so.\n // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,\n // whereas in other browsers they will be undefined.\n this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);\n this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);\n this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);\n this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);\n this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);\n this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);\n this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);\n\n } else {\n this.ignoreCase_ = !!opt_ignoreCase;\n this.queryData_ = new goog.Uri.QueryData(null, 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 'use strict';\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(goog.Uri.encodeSpecialChars_(\n path,\n 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 '#',\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 'use strict';\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().slice(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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n return !!this.scheme_;\n};\n\n\n/**\n * @return {string} The decoded user info.\n */\ngoog.Uri.prototype.getUserInfo = function() {\n 'use strict';\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 'use strict';\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 'use strict';\n return !!this.userInfo_;\n};\n\n\n/**\n * @return {string} The decoded domain.\n */\ngoog.Uri.prototype.getDomain = function() {\n 'use strict';\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 'use strict';\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 'use strict';\n return !!this.domain_;\n};\n\n\n/**\n * @return {?number} The port number.\n */\ngoog.Uri.prototype.getPort = function() {\n 'use strict';\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 'use strict';\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 'use strict';\n return this.port_ != null;\n};\n\n\n/**\n * @return {string} The decoded path.\n */\ngoog.Uri.prototype.getPath = function() {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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, 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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n this.enforceReadOnly();\n\n if (!Array.isArray(values)) {\n values = [String(values)];\n }\n\n this.queryData_.setValues(key, values);\n\n return this;\n};\n\n\n/**\n * Returns the value<b>s</b> for a given cgi parameter as a list of decoded\n * query parameter values.\n * @param {string} name The parameter to get values for.\n * @return {!Array<?>} The values for a given cgi parameter as a list of\n * decoded query parameter values.\n */\ngoog.Uri.prototype.getParameterValues = function(name) {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n if (typeof unescapedPart === 'string') {\n var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);\n if (opt_removeDoubleEncoding) {\n // encodeURI double-escapes %XX sequences used to represent restricted\n // characters in some URI components, remove the double escaping here.\n encoded = goog.Uri.removeDoubleEncoding_(encoded);\n }\n return encoded;\n }\n return null;\n};\n\n\n/**\n * Converts a character in [\\01-\\177] to its unicode character equivalent.\n * @param {string} ch One character string.\n * @return {string} Encoded string.\n * @private\n */\ngoog.Uri.encodeChar_ = function(ch) {\n 'use strict';\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 'use strict';\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 'use strict';\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 {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_ignoreCase) {\n 'use strict';\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 {?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 'use strict';\n if (!this.keyMap_) {\n this.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map());\n this.count_ = 0;\n if (this.encodedQuery_) {\n var self = this;\n goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {\n 'use strict';\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.collections.maps.MapLike<string, ?>|!Object} map Map of string\n * parameter 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 {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_ignoreCase) {\n 'use strict';\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, opt_ignoreCase);\n var values = goog.structs.getValues(map);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = values[i];\n if (!Array.isArray(value)) {\n queryData.add(key, value);\n } else {\n queryData.setValues(key, value);\n }\n }\n return queryData;\n};\n\n\n/**\n * Creates a new query data instance from parallel arrays of parameter names\n * and values. Allows for duplicate parameter names. Throws an error if the\n * lengths of the arrays differ.\n *\n * @param {!Array<string>} keys Parameter names.\n * @param {!Array<?>} values Parameter values.\n * @param {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_ignoreCase) {\n 'use strict';\n if (keys.length != values.length) {\n throw new Error('Mismatched lengths for keys/values');\n }\n var queryData = new goog.Uri.QueryData(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 'use strict';\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 'use strict';\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 'use strict';\n this.ensureKeyMapInitialized_();\n\n key = this.getKeyName_(key);\n if (this.keyMap_.has(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_.delete(key);\n }\n return false;\n};\n\n\n/**\n * Clears the parameters.\n */\ngoog.Uri.QueryData.prototype.clear = function() {\n 'use strict';\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 'use strict';\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 'use strict';\n this.ensureKeyMapInitialized_();\n key = this.getKeyName_(key);\n return this.keyMap_.has(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 'use strict';\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 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(values, key) {\n 'use strict';\n values.forEach(function(value) {\n 'use strict';\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 'use strict';\n this.ensureKeyMapInitialized_();\n // We need to get the values to know how many keys to add.\n const vals = Array.from(this.keyMap_.values());\n const keys = Array.from(this.keyMap_.keys());\n const rv = [];\n for (let i = 0; i < keys.length; i++) {\n const val = vals[i];\n for (let 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 'use strict';\n this.ensureKeyMapInitialized_();\n let rv = [];\n if (typeof opt_key === 'string') {\n if (this.containsKey(opt_key)) {\n rv = rv.concat(this.keyMap_.get(this.getKeyName_(opt_key)));\n }\n } else {\n // Return all values.\n const values = Array.from(this.keyMap_.values());\n for (let i = 0; i < values.length; i++) {\n rv = rv.concat(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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n if (this.encodedQuery_) {\n return this.encodedQuery_;\n }\n\n if (!this.keyMap_) {\n return '';\n }\n\n const 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 const keys = Array.from(this.keyMap_.keys());\n for (var i = 0; i < keys.length; i++) {\n const key = keys[i];\n const encodedKey = goog.string.urlEncode(key);\n const 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 'use strict';\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 'use strict';\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 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\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 'use strict';\n var rv = new goog.Uri.QueryData();\n rv.encodedQuery_ = this.encodedQuery_;\n if (this.keyMap_) {\n rv.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map(this.keyMap_));\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 'use strict';\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 'use strict';\n var resetKeys = ignoreCase && !this.ignoreCase_;\n if (resetKeys) {\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\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.collections.maps.MapLike<?,\n * ?>|?Object)} var_args The object from which key value pairs will be\n * copied. Note: does not 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 'use strict';\n for (var i = 0; i < arguments.length; i++) {\n var data = arguments[i];\n goog.structs.forEach(data, function(value, key) {\n 'use strict';\n this.add(key, value);\n }, this);\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The dispose method is used to clean up references and\n * resources.\n */\n\ngoog.module('goog.dispose');\ngoog.module.declareLegacyNamespace();\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 */\nfunction dispose(obj) {\n if (obj && typeof obj.dispose == 'function') {\n obj.dispose();\n }\n}\nexports = dispose;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Codec functions of the v8 wire protocol. Eventually we'd want\n * to support pluggable wire-format to improve wire efficiency and to enable\n * binary encoding. Such support will require an interface class, which\n * will be added later.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WireV8');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.json.NativeJsonProcessor');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.structs');\ngoog.requireType('goog.string.Parser');\n\n\n\n/**\n * The v8 codec class.\n *\n * @constructor\n * @struct\n */\ngoog.labs.net.webChannel.WireV8 = function() {\n 'use strict';\n /**\n * Parser for a response payload. The parser should return an array.\n * @private {!goog.string.Parser}\n */\n this.parser_ = new goog.json.NativeJsonProcessor();\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * Encodes a standalone message into the wire format.\n *\n * May throw exception if the message object contains any invalid elements.\n *\n * @param {!Object|!goog.collections.maps.MapLike} message The message data.\n * V8 only support JS objects (or Map).\n * @param {!Array<string>} buffer The text buffer to write the message to.\n * @param {string=} opt_prefix The prefix for each field of the object.\n */\nWireV8.prototype.encodeMessage = function(message, buffer, opt_prefix) {\n 'use strict';\n const prefix = opt_prefix || '';\n try {\n goog.structs.forEach(message, function(value, key) {\n 'use strict';\n let encodedValue = value;\n if (goog.isObject(value)) {\n encodedValue = goog.json.serialize(value);\n } // keep the fast-path for primitive types\n buffer.push(prefix + key + '=' + encodeURIComponent(encodedValue));\n });\n } catch (ex) {\n // We send a map here because lots of the retry logic relies on map IDs,\n // so we have to send something (possibly redundant).\n buffer.push(\n prefix + 'type' +\n '=' + encodeURIComponent('_badmap'));\n throw ex;\n }\n};\n\n\n/**\n * Encodes all the buffered messages of the forward channel.\n *\n * @param {!Array<Wire.QueuedMap>} messageQueue The message data.\n * V8 only support JS objects.\n * @param {number} count The number of messages to be encoded.\n * @param {?function(!Object)} badMapHandler Callback for bad messages.\n * @return {string} the encoded messages\n */\nWireV8.prototype.encodeMessageQueue = function(\n messageQueue, count, badMapHandler) {\n 'use strict';\n let offset = -1;\n while (true) {\n const sb = ['count=' + count];\n // To save a bit of bandwidth, specify the base mapId and the rest as\n // offsets from it.\n if (offset == -1) {\n if (count > 0) {\n offset = messageQueue[0].mapId;\n sb.push('ofs=' + offset);\n } else {\n offset = 0;\n }\n } else {\n sb.push('ofs=' + offset);\n }\n let done = true;\n for (let i = 0; i < count; i++) {\n let mapId = messageQueue[i].mapId;\n const map = messageQueue[i].map;\n mapId -= offset;\n if (mapId < 0) {\n // redo the encoding in case of retry/reordering, plus extra space\n offset = Math.max(0, messageQueue[i].mapId - 100);\n done = false;\n continue;\n }\n try {\n this.encodeMessage(map, sb, 'req' + mapId + '_');\n } catch (ex) {\n if (badMapHandler) {\n badMapHandler(map);\n }\n }\n }\n if (done) {\n return sb.join('&');\n }\n }\n};\n\n\n/**\n * Decodes a standalone message received from the wire. May throw exception\n * if text is ill-formatted.\n *\n * Must be valid JSON as it is insecure to use eval() to decode JS literals;\n * and eval() is disallowed in Chrome apps too.\n *\n * Invalid JS literals include null array elements, quotas etc.\n *\n * @param {string} messageText The string content as received from the wire.\n * @return {*} The decoded message object.\n */\nWireV8.prototype.decodeMessage = function(messageText) {\n 'use strict';\n const response = this.parser_.parse(messageText);\n goog.asserts.assert(Array.isArray(response)); // throw exception\n return response;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Wrapper class for handling XmlHttpRequests.\n *\n * One off requests can be sent through goog.net.XhrIo.send() or an\n * instance can be created to send multiple requests. Each request uses its\n * own XmlHttpRequest object and handles clearing of the event callback to\n * ensure no leaks.\n *\n * XhrIo is event based, it dispatches events on success, failure, finishing,\n * ready-state change, or progress (download and upload).\n *\n * The ready-state or timeout event fires first, followed by\n * a generic completed event. Then the abort, error, or success event\n * is fired as appropriate. Progress events are fired as they are\n * received. Lastly, the ready event will fire to indicate that the\n * object may be used to make another request.\n *\n * The error event may also be called before completed and\n * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.\n *\n * This class does not support multiple requests, queuing, or prioritization.\n *\n * When progress events are supported by the browser, and progress is\n * enabled via .setProgressEventsEnabled(true), the\n * goog.net.EventType.PROGRESS event will be the re-dispatched browser\n * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event\n * will be fired for download and upload progress respectively.\n */\n\n\ngoog.provide('goog.net.XhrIo');\ngoog.provide('goog.net.XhrIo.ResponseType');\n\ngoog.require('goog.Timer');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\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.uri.utils');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.net.XhrLike');\ngoog.requireType('goog.net.XmlHttpFactory');\n\ngoog.scope(function() {\n\n'use strict';\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 'use strict';\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 {!Map<string,string>}\n */\n this.headers = new 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 state 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\n /**\n * Specification for Trust Token operations (issuance, signing, and\n * redemption).\n * @private {?TrustTokenAttributeType}\n */\n this.trustToken_ = null;\n};\ngoog.inherits(goog.net.XhrIo, goog.events.EventTarget);\n\nconst 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\nconst 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\nconst HTTP_SCHEME_PATTERN = goog.net.XhrIo.HTTP_SCHEME_PATTERN;\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.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the 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 'use strict';\n const 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 'use strict';\n const 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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n return this.progressEventsEnabled_;\n};\n\n/**\n * Specify a Trust Tokens operation to execute alongside the request.\n * @param {!TrustTokenAttributeType} trustToken a Trust Tokens operation to\n * execute.\n */\ngoog.net.XhrIo.prototype.setTrustToken = function(trustToken) {\n 'use strict';\n this.trustToken_ = trustToken;\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.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @suppress {strictMissingProperties} Added to tighten compiler checks\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 'use strict';\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 const 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 /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.xhr_.onprogress = goog.bind(function(e) {\n 'use strict';\n this.onProgressHandler_(e, true);\n }, this);\n if (this.xhr_.upload) {\n /**\n * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\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 const content = opt_content || '';\n\n const headers = new Map(this.headers);\n\n // Add headers specific to this request\n if (opt_headers) {\n if (Object.getPrototypeOf(opt_headers) === Object.prototype) {\n for (let key in opt_headers) {\n headers.set(key, opt_headers[key]);\n }\n } else if (\n typeof opt_headers.keys === 'function' &&\n typeof opt_headers.get === 'function') {\n for (const key of opt_headers.keys()) {\n headers.set(key, opt_headers.get(key));\n }\n } else {\n throw new Error(\n 'Unknown input type for opt_headers: ' + String(opt_headers));\n }\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 const contentTypeKey =\n Array.from(headers.keys())\n .find(\n header => goog.string.caseInsensitiveEquals(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, header));\n\n const 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 for (const [key, value] of headers) {\n this.xhr_.setRequestHeader(key, value);\n }\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 /** @suppress {strictMissingProperties} Added to tighten compiler checks */\n this.xhr_.withCredentials = this.withCredentials_;\n }\n\n if ('setTrustToken' in this.xhr_ && this.trustToken_) {\n try {\n this.xhr_.setTrustToken(this.trustToken_);\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error SetTrustToken: ' + err.message));\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_,\n 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 'use strict';\n return goog.userAgent.IE &&\n typeof xhr[goog.net.XhrIo.XHR2_TIMEOUT_] === 'number' &&\n xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_] !== undefined;\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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(goog.net.XhrIo.buildProgressEvent_(\n e,\n 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 'use strict';\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 'use strict';\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 const xhr = this.xhr_;\n const clearedOnReadyStateChange =\n this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?\n () => {} :\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 'use strict';\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 'use strict';\n return !!this.xhr_;\n};\n\n\n/**\n * @return {boolean} Whether the request has completed.\n */\ngoog.net.XhrIo.prototype.isComplete = function() {\n 'use strict';\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 'use strict';\n const 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 'use strict';\n const scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));\n return 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 'use strict';\n return this.xhr_ ?\n /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :\n goog.net.XmlHttp.ReadyState.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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n if (!this.xhr_) {\n return undefined;\n }\n\n let 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 * @suppress {strictMissingProperties} Added to tighten compiler checks\n */\ngoog.net.XhrIo.prototype.getResponse = function() {\n 'use strict';\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_,\n '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 'use strict';\n if (!this.xhr_ || !this.isComplete()) {\n return undefined;\n }\n\n const value = this.xhr_.getResponseHeader(key);\n return value === null ? undefined : value;\n};\n\n\n/**\n * Gets the text of all the headers in the response.\n * Will only return correct result after ready state reaches `LOADED` (i.e.\n * `HEADERS_RECEIVED` as per MDN).\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllResponseHeaders = function() {\n 'use strict';\n // getAllResponseHeaders can return null if no response has been received,\n // ensure we always return an empty string.\n return this.xhr_ &&\n this.getReadyState() >= goog.net.XmlHttp.ReadyState.LOADED ?\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 'use strict';\n // TODO(user): Make this function parse headers as per the spec\n // (https://tools.ietf.org/html/rfc2616#section-4.2).\n\n const headersObject = {};\n const headersArray = this.getAllResponseHeaders().split('\\r\\n');\n for (let i = 0; i < headersArray.length; i++) {\n if (goog.string.isEmptyOrWhitespace(headersArray[i])) {\n continue;\n }\n const keyValue =\n goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);\n const key = keyValue[0];\n let value = keyValue[1];\n\n if (typeof value !== 'string') {\n // There must be a value but it can be the empty string.\n continue;\n }\n\n // Whitespace at the start and end of the value is meaningless.\n value = value.trim();\n // The key should not contain whitespace but we currently ignore that.\n\n const values = headersObject[key] || [];\n headersObject[key] = values;\n values.push(value);\n }\n\n return goog.object.map(headersObject, function(values) {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n return typeof this.lastError_ === 'string' ? this.lastError_ :\n String(this.lastError_);\n};\n\n\n/**\n * Adds the last method, status and URI to the message. This is used to add\n * this information to the logging calls.\n * @param {string} msg The message text that we want to add the extra text to.\n * @return {string} The message with the extra text appended.\n * @private\n */\ngoog.net.XhrIo.prototype.formatMsg_ = function(msg) {\n 'use strict';\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 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n });\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A pool of forward channel requests to enable real-time\n * messaging from the client to server.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.ForwardChannelRequestPool');\n\ngoog.module.declareLegacyNamespace();\n\nconst ChannelRequest = goog.require('goog.labs.net.webChannel.ChannelRequest');\nconst Wire = goog.require('goog.labs.net.webChannel.Wire');\nconst array = goog.require('goog.array');\nconst googString = goog.require('goog.string');\n\n\n/**\n * This class represents the state of all forward channel requests.\n *\n * @param {number=} opt_maxPoolSize The maximum pool size.\n *\n * @struct @constructor @final\n */\nconst ForwardChannelRequestPool = function(opt_maxPoolSize) {\n /**\n * The max pool size as configured.\n *\n * @private {number}\n */\n this.maxPoolSizeConfigured_ =\n opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;\n\n /**\n * The current size limit of the request pool. This limit is meant to be\n * read-only after the channel is fully opened.\n *\n * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also\n * configurable.\n *\n * @private {number}\n */\n this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?\n this.maxPoolSizeConfigured_ :\n 1;\n\n /**\n * The container for all the pending request objects.\n *\n * @private {?Set<?ChannelRequest>}\n */\n this.requestPool_ = null;\n\n if (this.maxSize_ > 1) {\n this.requestPool_ = new Set();\n }\n\n /**\n * The single request object when the pool size is limited to one.\n *\n * @private {?ChannelRequest}\n */\n this.request_ = null;\n\n /**\n * Saved pending messages when the pool is cancelled.\n *\n * @private {!Array<Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n};\n\n\n/**\n * The default size limit of the request pool.\n *\n * @private {number}\n */\nForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;\n\n\n/**\n * @return {boolean} True if SPDY or HTTP2 is enabled. Uses chrome-specific APIs\n * as a fallback and will always return false for other browsers where\n * PerformanceNavigationTiming is not available.\n * @private\n */\nForwardChannelRequestPool.isSpdyOrHttp2Enabled_ = function() {\n if (goog.global.PerformanceNavigationTiming) {\n const entrys = /** @type {!Array<!PerformanceNavigationTiming>} */ (\n goog.global.performance.getEntriesByType('navigation'));\n return entrys.length > 0 &&\n (entrys[0].nextHopProtocol == 'hq' ||\n entrys[0].nextHopProtocol == 'h2');\n }\n return !!(\n goog.global.chrome && goog.global.chrome.loadTimes &&\n goog.global.chrome.loadTimes() &&\n goog.global.chrome.loadTimes().wasFetchedViaSpdy);\n};\n\n\n/**\n * Once we know the client protocol (from the handshake), check if we need\n * enable the request pool accordingly. This is more robust than using\n * browser-internal APIs (specific to Chrome).\n *\n * @param {string} clientProtocol The client protocol\n */\nForwardChannelRequestPool.prototype.applyClientProtocol = function(\n clientProtocol) {\n if (this.requestPool_) {\n return;\n }\n\n if (googString.contains(clientProtocol, 'spdy') ||\n googString.contains(clientProtocol, 'quic') ||\n googString.contains(clientProtocol, 'h2')) {\n this.maxSize_ = this.maxPoolSizeConfigured_;\n this.requestPool_ = new Set();\n if (this.request_) {\n this.addRequest(this.request_);\n this.request_ = null;\n }\n }\n};\n\n\n/**\n * @return {boolean} True if the pool is full.\n */\nForwardChannelRequestPool.prototype.isFull = function() {\n if (this.request_) {\n return true;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size >= this.maxSize_;\n }\n\n return false;\n};\n\n\n/**\n * @return {number} The current size limit.\n */\nForwardChannelRequestPool.prototype.getMaxSize = function() {\n return this.maxSize_;\n};\n\n\n/**\n * @return {number} The number of pending requests in the pool.\n */\nForwardChannelRequestPool.prototype.getRequestCount = function() {\n if (this.request_) {\n return 1;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size;\n }\n\n return 0;\n};\n\n\n/**\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} True if the request is a included inside the pool.\n */\nForwardChannelRequestPool.prototype.hasRequest = function(req) {\n if (this.request_) {\n return this.request_ == req;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.has(req);\n }\n\n return false;\n};\n\n\n/**\n * Adds a new request to the pool.\n *\n * @param {!ChannelRequest} req The new channel request.\n */\nForwardChannelRequestPool.prototype.addRequest = function(req) {\n if (this.requestPool_) {\n this.requestPool_.add(req);\n } else {\n this.request_ = req;\n }\n};\n\n\n/**\n * Removes the given request from the pool.\n *\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} Whether the request has been removed from the pool.\n */\nForwardChannelRequestPool.prototype.removeRequest = function(req) {\n if (this.request_ && this.request_ == req) {\n this.request_ = null;\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.has(req)) {\n this.requestPool_.delete(req);\n return true;\n }\n\n return false;\n};\n\n\n/**\n * Clears the pool and cancel all the pending requests.\n */\nForwardChannelRequestPool.prototype.cancel = function() {\n // save any pending messages\n this.pendingMessages_ = this.getPendingMessages();\n\n if (this.request_) {\n this.request_.cancel();\n this.request_ = null;\n return;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n }\n this.requestPool_.clear();\n }\n};\n\n\n/**\n * @return {boolean} Whether there are any pending requests.\n */\nForwardChannelRequestPool.prototype.hasPendingRequest = function() {\n return (this.request_ != null) ||\n (this.requestPool_ != null && this.requestPool_.size !== 0);\n};\n\n\n/**\n * @return {!Array<Wire.QueuedMap>} All the pending messages from the pool,\n * as a new array.\n */\nForwardChannelRequestPool.prototype.getPendingMessages = function() {\n if (this.request_ != null) {\n return this.pendingMessages_.concat(this.request_.getPendingMessages());\n }\n\n if (this.requestPool_ != null && this.requestPool_.size !== 0) {\n let result = this.pendingMessages_;\n for (const val of this.requestPool_.values()) {\n result = result.concat(val.getPendingMessages());\n }\n return result;\n }\n\n return array.clone(this.pendingMessages_);\n};\n\n\n/**\n * Records pending messages, e.g. when a request receives a failed response.\n *\n * @param {!Array<Wire.QueuedMap>} messages Pending messages.\n */\nForwardChannelRequestPool.prototype.addPendingMessages = function(messages) {\n this.pendingMessages_ = this.pendingMessages_.concat(messages);\n};\n\n\n/**\n * Clears any recorded pending messages.\n */\nForwardChannelRequestPool.prototype.clearPendingMessages = function() {\n this.pendingMessages_.length = 0;\n};\n\n\n/**\n * Cancels all pending requests and force the completion of channel requests.\n *\n * Need go through the standard onRequestComplete logic to expose the max-retry\n * failure in the standard way.\n *\n * @param {function(!ChannelRequest)} onComplete The completion callback.\n * @return {boolean} true if any request has been forced to complete.\n */\nForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {\n if (this.request_ != null) {\n this.request_.cancel();\n onComplete(this.request_);\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n onComplete(val);\n }\n return true;\n }\n\n return false;\n};\n\nexports = ForwardChannelRequestPool;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Generics method for collection-like classes and objects.\n *\n *\n * This file contains functions to work with collections. It supports using\n * Map, Set, Array and Object and other classes that implement collection-like\n * methods.\n * @suppress {strictMissingProperties}\n */\n\n\ngoog.provide('goog.structs');\n\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n// We treat an object as a dictionary if it has getKeys or it is an object that\n// isn't arrayLike.\n\n\n/**\n * Returns the number of values in the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {number} The number of values in the collection-like object.\n */\ngoog.structs.getCount = function(col) {\n 'use strict';\n if (col.getCount && typeof col.getCount == 'function') {\n return col.getCount();\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return col.length;\n }\n return goog.object.getCount(col);\n};\n\n\n/**\n * Returns the values of the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {!Array<?>} The values in the collection-like object.\n */\ngoog.structs.getValues = function(col) {\n 'use strict';\n if (col.getValues && typeof col.getValues == 'function') {\n return col.getValues();\n }\n // ES6 Map and Set both define a values function that returns an iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if ((typeof Map !== 'undefined' && col instanceof Map) ||\n (typeof Set !== 'undefined' && col instanceof Set)) {\n return Array.from(col.values());\n }\n if (typeof col === 'string') {\n return col.split('');\n }\n if (goog.isArrayLike(col)) {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(col[i]);\n }\n return rv;\n }\n return goog.object.getValues(col);\n};\n\n\n/**\n * Returns the keys of the collection. Some collections have no notion of\n * keys/indexes and this function will return undefined in those cases.\n * @param {Object} col The collection-like object.\n * @return {!Array|undefined} The keys in the collection.\n */\ngoog.structs.getKeys = function(col) {\n 'use strict';\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 // ES6 Map and Set both define a keys function that returns an iterator. For\n // Sets this iterates over the same values as the values iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if (typeof Map !== 'undefined' && col instanceof Map) {\n return Array.from(col.keys());\n }\n // Unlike the native Set, goog.structs.Set does not expose keys as the values.\n if (typeof Set !== 'undefined' && col instanceof Set) {\n return undefined;\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(i);\n }\n return rv;\n }\n\n return goog.object.getKeys(col);\n};\n\n\n/**\n * Whether the collection contains the given value. This is O(n) and uses\n * equals (==) to test the existence.\n * @param {Object} col The collection-like object.\n * @param {*} val The value to check for.\n * @return {boolean} True if the map contains the value.\n */\ngoog.structs.contains = function(col, val) {\n 'use strict';\n if (col.contains && typeof col.contains == 'function') {\n return col.contains(val);\n }\n if (col.containsValue && typeof col.containsValue == 'function') {\n return col.containsValue(val);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.contains(/** @type {!Array<?>} */ (col), val);\n }\n return goog.object.containsValue(col, val);\n};\n\n\n/**\n * Whether the collection is empty.\n * @param {Object} col The collection-like object.\n * @return {boolean} True if empty.\n */\ngoog.structs.isEmpty = function(col) {\n 'use strict';\n if (col.isEmpty && typeof col.isEmpty == 'function') {\n return col.isEmpty();\n }\n\n // We do not use goog.string.isEmptyOrWhitespace because here we treat the\n // string as\n // collection and as such even whitespace matters\n\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return /** @type {!Array<?>} */ (col).length === 0;\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 * @return {void}\n */\ngoog.structs.clear = function(col) {\n 'use strict';\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 * @return {void}\n * @template T,S\n * @deprecated Use a more specific method, e.g. native Array.prototype.forEach,\n * or for-of.\n */\ngoog.structs.forEach = function(col, f, opt_obj) {\n 'use strict';\n if (col.forEach && typeof col.forEach == 'function') {\n col.forEach(f, opt_obj);\n } else if (goog.isArrayLike(col) || typeof col === 'string') {\n Array.prototype.forEach.call(/** @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 'use strict';\n if (typeof col.filter == 'function') {\n return col.filter(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.filter.call(\n /** @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 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 'use strict';\n if (typeof col.map == 'function') {\n return col.map(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.map.call(/** @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 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 'use strict';\n if (typeof col.some == 'function') {\n return col.some(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.some.call(\n /** @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 'use strict';\n if (typeof col.every == 'function') {\n return col.every(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.every.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for string manipulation.\n */\n\n\n/**\n * Namespace for string utilities\n */\ngoog.provide('goog.string');\ngoog.provide('goog.string.Unicode');\n\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Enables HTML escaping of lowercase letter \"e\" which helps\n * with detection of double-escaping as this letter is frequently used.\n */\ngoog.string.DETECT_DOUBLE_ESCAPING =\n goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);\n\n\n/**\n * @define {boolean} Whether to force non-dom html unescaping.\n */\ngoog.string.FORCE_NON_DOM_HTML_UNESCAPING =\n goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);\n\n\n/**\n * Common Unicode string characters.\n * @enum {string}\n */\ngoog.string.Unicode = {\n NBSP: '\\xa0',\n ZERO_WIDTH_SPACE: '\\u200b' // This is equivalent to <wbr>.\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 'use strict';\n const splitParts = str.split('%s');\n let returnString = '';\n\n const 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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 const tokens1 = str1.toLowerCase().match(tokenizerRegExp);\n const tokens2 = str2.toLowerCase().match(tokenizerRegExp);\n\n const count = Math.min(tokens1.length, tokens2.length);\n\n for (let i = 0; i < count; i++) {\n const a = tokens1[i];\n const 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 const num1 = parseInt(a, 10);\n if (!isNaN(num1)) {\n const 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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n /** @type {!Object<string, string>} */\n const seen = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"'};\n /** @type {!Element} */\n let 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 'use strict';\n // Check for cached entity.\n let 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 const n = Number('0' + entity.slice(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 'use strict';\n return str.replace(/&([^;]+);/g, function(s, entity) {\n 'use strict';\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 const n = Number('0' + entity.slice(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 'use strict';\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 'use strict';\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 'use strict';\n const length = quoteChars.length;\n for (let i = 0; i < length; i++) {\n const 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 'use strict';\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 'use strict';\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 const endPoint = str.length - opt_trailingChars;\n const 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 let half = Math.floor(chars / 2);\n const 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 'use strict';\n s = String(s);\n const sb = ['\"'];\n for (let i = 0; i < s.length; i++) {\n const ch = s.charAt(i);\n const 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 'use strict';\n const sb = [];\n for (let 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 'use strict';\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 let rv = c;\n const 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 'use strict';\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 'use strict';\n let 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.slice(0, index) + s.slice(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 'use strict';\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 'use strict';\n const 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 'use strict';\n const 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 'use strict';\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 'use strict';\n // The native method is over 100 times faster than the alternative.\n return string.repeat(length);\n} : function(string, length) {\n 'use strict';\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 'use strict';\n if (!Number.isFinite(num)) return String(num);\n let s =\n (opt_precision !== undefined) ? num.toFixed(opt_precision) : String(num);\n let index = s.indexOf('.');\n if (index === -1) {\n index = s.length;\n }\n const sign = s[0] === '-' ? '-' : '';\n if (sign) {\n s = s.substring(1);\n }\n return sign + 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 'use strict';\n return obj == null ? '' : String(obj);\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 'use strict';\n const 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 'use strict';\n let result = 0;\n for (let 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 'use strict';\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 'use strict';\n const 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 'use strict';\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 'use strict';\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 'use strict';\n return String(str).replace(/\\-([a-z])/g, function(all, match) {\n 'use strict';\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 'use strict';\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 'use strict';\n let delimiters = (typeof opt_delimiters === 'string') ?\n goog.string.regExpEscape(opt_delimiters) :\n '\\\\s';\n\n // For IE8, we need to prevent using an empty character set. Otherwise,\n // incorrect matching will occur.\n delimiters = delimiters ? '|[' + delimiters + ']+' : '';\n\n const regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');\n return str.replace(regexp, function(all, p1, p2) {\n 'use strict';\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 'use strict';\n return String(str.charAt(0)).toUpperCase() +\n String(str.slice(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 'use strict';\n // Force finite numbers to strings.\n if (isFinite(value)) {\n value = String(value);\n }\n\n if (typeof value === 'string') {\n // If the string starts with '0x' or '-0x', parse as hex.\n return /^\\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10);\n }\n\n return NaN;\n};\n\n\n/**\n * Splits a string on a separator a limited number of times.\n *\n * This implementation is more similar to Python or Java, where the limit\n * parameter specifies the maximum number of splits rather than truncating\n * the number of results.\n *\n * See http://docs.python.org/2/library/stdtypes.html#str.split\n * See JavaDoc: http://goo.gl/F2AsY\n * See Mozilla reference: http://goo.gl/dZdZs\n *\n * @param {string} str String to split.\n * @param {string} separator The separator.\n * @param {number} limit The limit to the number of splits. The resulting array\n * will have a maximum length of limit+1. Negative numbers are the same\n * as zero.\n * @return {!Array<string>} The string, split.\n */\ngoog.string.splitLimit = function(str, separator, limit) {\n 'use strict';\n const parts = str.split(separator);\n const 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 'use strict';\n if (!separators) {\n return str;\n } else if (typeof separators == 'string') {\n separators = [separators];\n }\n\n let lastSeparatorIndex = -1;\n for (let i = 0; i < separators.length; i++) {\n if (separators[i] == '') {\n continue;\n }\n const 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 'use strict';\n const v0 = [];\n const 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 (let i = 0; i < b.length + 1; i++) {\n v0[i] = i;\n }\n\n for (let i = 0; i < a.length; i++) {\n v1[0] = i + 1;\n\n for (let j = 0; j < b.length; j++) {\n const 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 (let j = 0; j < v0.length; j++) {\n v0[j] = v1[j];\n }\n }\n\n return v1[b.length];\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple utilities for dealing with URI strings.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * This is intended to be a lightweight alternative to constructing goog.Uri\n * objects. Whereas goog.Uri adds several kilobytes to the binary regardless\n * of how much of its functionality you use, this is designed to be a set of\n * mostly-independent utilities so that the compiler includes only what is\n * necessary for the task. Estimated savings of porting is 5k pre-gzip and\n * 1.5k post-gzip. To ensure the savings remain, future developers should\n * avoid adding new functionality to existing functions, but instead create\n * new ones and factor out shared code.\n *\n * Many of these utilities have limited functionality, tailored to common\n * cases. The query parameter utilities assume that the parameter keys are\n * already encoded, since most keys are compile-time alphanumeric strings. The\n * query parameter mutation utilities also do not tolerate fragment identifiers.\n *\n * By design, these functions can be slower than goog.Uri equivalents.\n * Repeated calls to some of functions may be quadratic in behavior for IE,\n * although the effect is somewhat limited given the 2kb limit.\n *\n * One advantage of the limited functionality here is that this approach is\n * less sensitive to differences in URI encodings than goog.Uri, since these\n * functions operate on strings directly, rather than decoding them and\n * then re-encoding.\n *\n * Uses features of RFC 3986 for parsing/formatting URIs:\n * http://www.ietf.org/rfc/rfc3986.txt\n */\n\ngoog.provide('goog.uri.utils');\ngoog.provide('goog.uri.utils.ComponentIndex');\ngoog.provide('goog.uri.utils.QueryArray');\ngoog.provide('goog.uri.utils.QueryValue');\ngoog.provide('goog.uri.utils.StandardQueryParam');\n\ngoog.require('goog.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 'use strict';\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 *\n * TODO(user): separate out the authority terminating characters once this\n * file is moved to ES6.\n * @type {!RegExp}\n * @private\n */\ngoog.uri.utils.splitRe_ = new RegExp(\n '^' + // Anchor against the entire string.\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. Can't use '.*' with 's' flag as Firefox\n // doesn't support the flag, and can't use an\n // \"everything set\" ([^]) as IE10 doesn't match any\n // characters with it.\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 * @type {?function(string)}\n * @private\n */\ngoog.uri.utils.urlPackageSupportLoggingHandler_ = null;\n\n/**\n * @param {?function(string)} handler The handler function to call when a URI\n * with a protocol that is better supported by the Closure URL package is\n * detected.\n */\ngoog.uri.utils.setUrlPackageSupportLoggingHandler = function(handler) {\n 'use strict';\n goog.uri.utils.urlPackageSupportLoggingHandler_ = handler;\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 'use strict';\n // See @return comment -- never null.\n var result = /** @type {!Array<string|undefined>} */ (\n uri.match(goog.uri.utils.splitRe_));\n if (goog.uri.utils.urlPackageSupportLoggingHandler_ &&\n ['http', 'https', 'ws', 'wss',\n 'ftp'].indexOf(result[goog.uri.utils.ComponentIndex.SCHEME]) >= 0) {\n goog.uri.utils.urlPackageSupportLoggingHandler_(uri);\n }\n return result;\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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.slice(0, -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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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.slice(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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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.slice(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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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.slice(0, questionIndex), queryData, uri.slice(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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n goog.asserts.assertString(key);\n if (Array.isArray(value)) {\n // Convince the compiler it's an array.\n goog.asserts.assertArray(value);\n for (var j = 0; j < value.length; j++) {\n // Convert to string explicitly, to short circuit the null and array\n // logic in this function -- this ensures that null and undefined get\n // written as literal 'null' and 'undefined', and arrays don't get\n // expanded out but instead encoded in the default way.\n goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);\n }\n } else if (value != null) {\n // Skip a top-level null or undefined entirely.\n pairs.push(\n key +\n // Check for empty string. Zero gets encoded into the url as literal\n // strings. For empty string, skip the equal sign, to be consistent\n // with UriBuilder.java.\n (value === '' ? '' : '=' + goog.string.urlEncode(value)));\n }\n};\n\n\n/**\n * Builds a query data string from a sequence of alternating keys and values.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues\n * Alternating keys and values. See the QueryArray typedef.\n * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {\n 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\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 'use strict';\n var value = (opt_value != null) ? '=' + goog.string.urlEncode(opt_value) : '';\n return goog.uri.utils.appendQueryDataToUri_(uri, key + value);\n};\n\n\n/**\n * Finds the next instance of a query parameter with the specified name.\n *\n * Does not instantiate any objects.\n *\n * @param {string} uri The URI to search. May contain a fragment identifier\n * if opt_hashIndex is specified.\n * @param {number} startIndex The index to begin searching for the key at. A\n * match may be found even if this is one character after the ampersand.\n * @param {string} keyEncoded The URI-encoded key.\n * @param {number} hashOrEndIndex Index to stop looking at. If a hash\n * mark is present, it should be its index, otherwise it should be the\n * length of the string.\n * @return {number} The position of the first character in the key's name,\n * immediately after either a question mark or a dot.\n * @private\n */\ngoog.uri.utils.findParam_ = function(\n uri, startIndex, keyEncoded, hashOrEndIndex) {\n 'use strict';\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 'use strict';\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 'use strict';\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 return goog.string.urlDecode(\n uri.slice(foundIndex, endPosition !== -1 ? endPosition : 0));\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 'use strict';\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 result.push(\n goog.string.urlDecode(uri.slice(foundIndex, Math.max(position, 0))));\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 'use strict';\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.slice(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 'use strict';\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 'use strict';\n var parts = goog.uri.utils.splitQueryData_(uri);\n var queryData = parts[1];\n var buffer = [];\n if (queryData) {\n queryData.split('&').forEach(function(pair) {\n 'use strict';\n var indexOfEquals = pair.indexOf('=');\n var name = indexOfEquals >= 0 ? pair.slice(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 'use strict';\n goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);\n\n // Remove any trailing '/'\n if (goog.string.endsWith(baseUri, '/')) {\n baseUri = baseUri.slice(0, -1);\n }\n // Remove any leading '/'\n if (goog.string.startsWith(path, '/')) {\n path = path.slice(1);\n }\n return '' + 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 'use strict';\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 'use strict';\n return goog.uri.utils.setParam(\n uri, goog.uri.utils.StandardQueryParam.RANDOM,\n goog.string.getRandomString());\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface and shared data structures for implementing\n * different wire protocol versions.\n */\ngoog.provide('goog.labs.net.webChannel.Wire');\ngoog.provide('goog.labs.net.webChannel.Wire.QueuedMap');\n\n\n\ngoog.require('goog.collections.maps');\n\n\n\n/**\n * The interface class.\n * @interface\n */\ngoog.labs.net.webChannel.Wire = class {\n constructor() {}\n};\n\n\n/**\n * The latest protocol version that this class supports. We request this version\n * from the server when opening the connection. Should match\n * LATEST_CHANNEL_VERSION on the server code.\n * @type {number}\n */\ngoog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION = 8;\n\n\n/**\n * The JSON field key for the raw data wrapper object.\n * @type {string}\n */\ngoog.labs.net.webChannel.Wire.RAW_DATA_KEY = '__data__';\n\n\n\n/**\n * Simple container class for a (mapId, map) pair.\n */\ngoog.labs.net.webChannel.Wire.QueuedMap = class {\n /**\n * @param {number} mapId The id for this map.\n * @param {!Object|!goog.collections.maps.MapLike} map The map itself.\n * @param {!Object=} opt_context The context associated with the map.\n */\n constructor(mapId, map, opt_context) {\n 'use strict';\n /**\n * The id for this map.\n * @type {number}\n */\n this.mapId = mapId;\n\n /**\n * The map itself.\n * @type {!Object|!goog.collections.maps.MapLike}\n */\n this.map = map;\n\n /**\n * The context for the map.\n * @type {Object}\n */\n this.context = opt_context || null;\n }\n\n /**\n * @return {number|undefined} the size of the raw JSON message or\n * undefined if the message is not encoded as a raw JSON message\n */\n getRawDataSize() {\n 'use strict';\n if (goog.labs.net.webChannel.Wire.RAW_DATA_KEY in this.map) {\n const data = this.map[goog.labs.net.webChannel.Wire.RAW_DATA_KEY];\n if (typeof data === 'string') {\n return data.length;\n }\n }\n\n return undefined;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Defines a class for parsing JSON using the browser's built in\n * JSON library.\n */\n\ngoog.module('goog.json.NativeJsonProcessor');\ngoog.module.declareLegacyNamespace();\n\nconst Parser = goog.require('goog.string.Parser');\nconst Stringifier = goog.require('goog.string.Stringifier');\nconst asserts = goog.require('goog.asserts');\nconst {Replacer, Reviver} = goog.require('goog.json.types');\n\n\n\n/**\n * A class that parses and stringifies JSON using the browser's built-in JSON\n * library.\n *\n\n * @implements {Parser}\n * @implements {Stringifier}\n * @final\n */\nexports = class {\n /**\n * @param {?Replacer=} opt_replacer An optional replacer to use during\n * serialization.\n * @param {?=} opt_reviver An optional reviver to use during\n * parsing.\n */\n constructor(opt_replacer, opt_reviver) {\n asserts.assert(goog.global['JSON'] !== undefined, 'JSON not defined');\n\n /**\n * @type {!Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n\n /**\n * @type {!Reviver|null|undefined}\n * @private\n */\n this.reviver_ = opt_reviver;\n };\n\n /**\n * Serializes an object or a value to a string.\n * Agnostic to the particular format of object and string.\n *\n * @param {*} object The object to stringify.\n * @return {string} A string representation of the input.\n * @override\n */\n stringify(object) {\n return goog.global['JSON'].stringify(object, this.replacer_);\n }\n\n /**\n * Parses a string into an object and returns the result.\n * Agnostic to the format of string and object.\n *\n * @param {string} s The string to parse.\n * @return {*} The object generated from the string.\n * @override\n */\n parse(s) {\n return goog.global['JSON'].parse(s, this.reviver_);\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for creating functions. Loosely inspired by these\n * java classes from the Guava library:\n * com.google.common.base.Functions\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Functions.html\n *\n * com.google.common.base.Predicates\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Predicates.html\n *\n * More about these can be found at\n * https://github.com/google/guava/wiki/FunctionalExplained\n */\n\n\ngoog.provide('goog.functions');\n\n\n/**\n * Creates a function that always returns the same value.\n * @param {T} retValue The value to return.\n * @return {function():T} The new function.\n * @template T\n */\ngoog.functions.constant = function(retValue) {\n 'use strict';\n return function() {\n 'use strict';\n return retValue;\n };\n};\n\n\n/**\n * Always returns false.\n * @type {function(...): boolean}\n */\ngoog.functions.FALSE = function() {\n 'use strict';\n return false;\n};\n\n\n/**\n * Always returns true.\n * @type {function(...): boolean}\n */\ngoog.functions.TRUE = function() {\n 'use strict';\n return true;\n};\n\n\n/**\n * Always returns `null`.\n * @type {function(...): null}\n */\ngoog.functions.NULL = function() {\n 'use strict';\n return null;\n};\n\n\n/**\n * Always returns `undefined`.\n * @type {function(...): undefined}\n */\ngoog.functions.UNDEFINED = function() {\n return undefined;\n};\n\n/**\n * Always returns `undefined` (loosely-typed version).\n * @type {!Function}\n */\ngoog.functions.EMPTY = /** @type {?} */ (goog.functions.UNDEFINED);\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 'use strict';\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 'use strict';\n return function() {\n 'use strict';\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 'use strict';\n return function() {\n 'use strict';\n throw err;\n };\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 'use strict';\n opt_numArgs = opt_numArgs || 0;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));\n };\n};\n\n\n/**\n * Creates a function that returns its nth argument.\n * @param {number} n The position of the return argument.\n * @return {!Function} A new function.\n */\ngoog.functions.nth = function(n) {\n 'use strict';\n return function() {\n 'use strict';\n return arguments[n];\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 'use strict';\n const rightArgs = Array.prototype.slice.call(arguments, 1);\n return function() {\n 'use strict';\n // Even in strict mode, IE10/11 and Edge (non-Chromium) use global context\n // when free-calling functions. To catch cases where people were using this\n // erroneously, we explicitly change the context to undefined to match\n // strict mode specifications.\n let self = /** @type {*} */ (this);\n if (self === goog.global) {\n self = undefined;\n }\n const newArgs = Array.prototype.slice.call(arguments);\n newArgs.push.apply(newArgs, rightArgs);\n return fn.apply(self, newArgs);\n };\n};\n\n\n/**\n * Given a function, create a new function that swallows its return value\n * and replaces it with a new one.\n * @param {Function} f A function.\n * @param {T} retValue A new return value.\n * @return {function(...?):T} A new function.\n * @template T\n */\ngoog.functions.withReturnValue = function(f, retValue) {\n 'use strict';\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 'use strict';\n return function(other) {\n 'use strict';\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 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n if (length) {\n result = functions[length - 1].apply(self, arguments);\n }\n\n for (let i = length - 2; i >= 0; i--) {\n result = functions[i].call(self, result);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that calls the functions passed in in sequence, and\n * returns the value of the last function. For example,\n * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).\n * @param {...Function} var_args A list of functions.\n * @return {!Function} A function that calls all inputs in sequence.\n */\ngoog.functions.sequence = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n for (let i = 0; i < length; i++) {\n result = functions[i].apply(self, arguments);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that returns true if each of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns false.\n * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ANDs its component\n * functions.\n */\ngoog.functions.and = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (!functions[i].apply(self, arguments)) {\n return false;\n }\n }\n return true;\n };\n};\n\n\n/**\n * Creates a function that returns true if any of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns true.\n * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ORs its component\n * functions.\n */\ngoog.functions.or = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (functions[i].apply(self, arguments)) {\n return true;\n }\n }\n return false;\n };\n};\n\n\n/**\n * Creates a function that returns the Boolean opposite of a provided function.\n * For example, (goog.functions.not(f))(x) is equivalent to !f(x).\n * @param {!Function} f The original function.\n * @return {function(...?):boolean} A function that delegates to f and returns\n * opposite.\n */\ngoog.functions.not = function(f) {\n 'use strict';\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return !f.apply(self, arguments);\n };\n};\n\n\n/**\n * Generic factory function to construct an object given the constructor\n * and the arguments. Intended to be bound to create object factories.\n *\n * Example:\n *\n * var factory = goog.partial(goog.functions.create, Class);\n *\n * @param {function(new:T, ...)} constructor The constructor for the Object.\n * @param {...*} var_args The arguments to be passed to the constructor.\n * @return {T} A new instance of the class given in `constructor`.\n * @template T\n * @deprecated This function does not work with ES6 class constructors. Use\n * arrow functions + spread args instead.\n */\ngoog.functions.create = function(constructor, var_args) {\n 'use strict';\n /**\n * @constructor\n * @final\n */\n const temp = function() {};\n temp.prototype = constructor.prototype;\n\n // obj will have constructor's prototype in its chain and\n // 'obj instanceof constructor' will be true.\n const obj = new temp();\n\n // obj is initialized by constructor.\n // arguments is only array-like so lacks shift(), but can be used with\n // the Array prototype function.\n constructor.apply(obj, Array.prototype.slice.call(arguments, 1));\n return obj;\n};\n\n\n/**\n * @define {boolean} Whether the return value cache should be used.\n * This should only be used to disable caches when testing.\n */\ngoog.functions.CACHE_RETURN_VALUE =\n goog.define('goog.functions.CACHE_RETURN_VALUE', true);\n\n\n/**\n * Gives a wrapper function that caches the return value of a parameterless\n * function when first called.\n *\n * When called for the first time, the given function is called and its\n * return value is cached (thus this is only appropriate for idempotent\n * functions). Subsequent calls will return the cached return value. This\n * allows the evaluation of expensive functions to be delayed until first used.\n *\n * To cache the return values of functions with parameters, see goog.memoize.\n *\n * @param {function():T} fn A function to lazily evaluate.\n * @return {function():T} A wrapped version the function.\n * @template T\n */\ngoog.functions.cacheReturnValue = function(fn) {\n 'use strict';\n let called = false;\n let value;\n\n return function() {\n 'use strict';\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 'use strict';\n // Keep a reference to the function that we null out when we're done with\n // it -- that way, the function can be GC'd when we're done with it.\n let inner = f;\n return function() {\n 'use strict';\n if (inner) {\n const tmp = inner;\n inner = null;\n tmp();\n }\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the Nth call will go through.\n *\n * This is particularly useful for batching up repeated actions where the\n * last action should win. This can be used, for example, for refreshing an\n * autocomplete pop-up every so often rather than updating with every keystroke,\n * since the final text typed by the user is the one that should produce the\n * final autocomplete results. For more stateful debouncing with support for\n * pausing, resuming, and canceling debounced actions, use\n * `goog.async.Debouncer`.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to debounce. The function will\n * only be called after the full interval has elapsed since the last call.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.debounce = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n goog.global.clearTimeout(timeout);\n const args = arguments;\n timeout = goog.global.setTimeout(function() {\n 'use strict';\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 'use strict';\n let timeout = 0;\n let shouldFire = false;\n let storedArgs = [];\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n if (shouldFire) {\n shouldFire = false;\n fire();\n }\n };\n\n const fire = function() {\n 'use strict';\n timeout = goog.global.setTimeout(handleTimeout, interval);\n let args = storedArgs;\n storedArgs = []; // Avoid a space leak by clearing stored arguments.\n f.apply(opt_scope, args);\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n storedArgs = 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 'use strict';\n let timeout = 0;\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n if (!timeout) {\n timeout = goog.global.setTimeout(handleTimeout, interval);\n f.apply(opt_scope, arguments);\n }\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.functions.isFunction = (val) => {\n return typeof val === 'function';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utility functions for managing networking, such as\n * testing network connectivity.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.netUtils');\n\ngoog.require('goog.Uri');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.scope(function() {\n'use strict';\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Default timeout to allow for URI pings.\n * @type {number}\n */\nnetUtils.NETWORK_TIMEOUT = 10000;\n\n\n/**\n * Pings the network with an image URI to check if an error is a server error\n * or user's network error.\n *\n * The caller needs to add a 'rand' parameter to make sure the response is\n * not fulfilled by browser cache.\n *\n * @param {function(boolean)} callback The function to call back with results.\n * @param {goog.Uri=} opt_imageUri The URI (of an image) to use for the network\n * test.\n */\nnetUtils.testNetwork = function(callback, opt_imageUri) {\n 'use strict';\n let uri = opt_imageUri;\n if (!uri) {\n // default google.com image\n uri = new goog.Uri('//www.google.com/images/cleardot.gif');\n\n if (!(goog.global.location && goog.global.location.protocol == 'http')) {\n uri.setScheme('https'); // e.g. chrome-extension\n }\n uri.makeUnique();\n }\n\n netUtils.testLoadImage(uri.toString(), netUtils.NETWORK_TIMEOUT, callback);\n};\n\n\n/**\n * Test loading the given image, retrying if necessary.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @param {number} retries The number of times to retry.\n * @param {!WebChannelDebug} channelDebug The debug object\n * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds\n * between retries - defaults to 0.\n */\nnetUtils.testLoadImageWithRetries = function(\n url, timeout, callback, retries, channelDebug, opt_pauseBetweenRetriesMS) {\n 'use strict';\n channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS);\n if (retries == 0) {\n // no more retries, give up\n callback(false);\n return;\n }\n\n const pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0;\n retries--;\n netUtils.testLoadImage(url, timeout, function(succeeded) {\n 'use strict';\n if (succeeded) {\n callback(true);\n } else {\n // try again\n goog.global.setTimeout(function() {\n 'use strict';\n netUtils.testLoadImageWithRetries(\n url, timeout, callback, retries, channelDebug, pauseBetweenRetries);\n }, pauseBetweenRetries);\n }\n });\n};\n\n\n/**\n * Test loading the given image.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.testLoadImage = function(url, timeout, callback) {\n 'use strict';\n const channelDebug = new WebChannelDebug();\n channelDebug.debug('TestLoadImage: loading ' + url);\n if (goog.global.Image) {\n const img = new Image();\n img.onload = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: loaded',\n true, callback);\n img.onerror = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: error',\n false, callback);\n img.onabort = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: abort',\n false, callback);\n img.ontimeout = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: timeout',\n false, callback);\n\n goog.global.setTimeout(function() {\n 'use strict';\n if (img.ontimeout) {\n img.ontimeout();\n }\n }, timeout);\n img.src = url;\n } else {\n // log ERROR_OTHER from environements where Image is not supported\n callback(false);\n }\n};\n\n\n/**\n * Wrap the image callback with debug and cleanup logic.\n * @param {!WebChannelDebug} channelDebug The WebChannelDebug object.\n * @param {!Image} img The image element.\n * @param {string} debugText The debug text.\n * @param {boolean} result The result of image loading.\n * @param {function(boolean)} callback The image callback.\n * @private\n */\nnetUtils.imageCallback_ = function(\n channelDebug, img, debugText, result, callback) {\n 'use strict';\n try {\n channelDebug.debug(debugText);\n netUtils.clearImageCallbacks_(img);\n callback(result);\n } catch (e) {\n channelDebug.dumpException(e);\n }\n};\n\n\n/**\n * Clears handlers to avoid memory leaks.\n * @param {Image} img The image to clear handlers from.\n * @private\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.clearImageCallbacks_ = function(img) {\n 'use strict';\n img.onload = null;\n img.onerror = null;\n img.onabort = null;\n img.ontimeout = null;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\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 * @record\n */\ngoog.net.FetchXmlHttpFactoryOptions = function() {\n /**\n * @type {!WorkerGlobalScope|undefined} The Service Worker global scope.\n */\n this.worker;\n\n /**\n * @type {boolean|undefined} Whether to store the FetchXmlHttp response as an\n * array of Uint8Arrays. If this is true then the 'responseType' attribute\n * must be empty.\n */\n this.streamBinaryChunks;\n};\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 * @param {!goog.net.FetchXmlHttpFactoryOptions} opts\n * @extends {goog.net.XmlHttpFactory}\n * @struct\n * @constructor\n */\ngoog.net.FetchXmlHttpFactory = function(opts) {\n 'use strict';\n goog.net.FetchXmlHttpFactory.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = opts.worker || null;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = opts.streamBinaryChunks || false;\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 'use strict';\n const instance =\n new goog.net.FetchXmlHttp(this.worker_, this.streamBinaryChunks_);\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 'use strict';\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 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n\n/**\n * FetchXmlHttp object constructor.\n * @param {?WorkerGlobalScope} worker\n * @param {boolean} streamBinaryChunks\n * @extends {goog.events.EventTarget}\n * @implements {goog.net.XhrLike}\n * @constructor\n * @struct\n */\ngoog.net.FetchXmlHttp = function(worker, streamBinaryChunks) {\n 'use strict';\n goog.net.FetchXmlHttp.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = worker;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = streamBinaryChunks;\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|!Array<!Uint8Array>}\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 'use strict';\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 'use strict';\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 const 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\n (this.worker_ || goog.global)\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 'use strict';\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 .catch(\n e => goog.log.warning(\n this.logger_, 'Fetch reader cancellation error.', e));\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_();\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 'use strict';\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.status = this.fetchResponse_.status;\n this.statusText = this.fetchResponse_.statusText;\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.currentReader_ =\n /** @type {!ReadableStreamDefaultReader} */ (response.body.getReader());\n if (this.streamBinaryChunks_) {\n if (this.responseType) {\n throw new Error(\n 'responseType must be empty for \"streamBinaryChunks\" mode responses.');\n }\n this.response = [];\n } else {\n this.response = this.responseText = '';\n this.textDecoder_ = new TextDecoder();\n }\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 'use strict';\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 {!IIterableResult} result\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleDataFromStream_ = function(result) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.streamBinaryChunks_ && result.value) {\n // When streamBinaryChunks_ is enabled, \"response\" is an array\n /** @type {!Array} */ (this.response)\n .push(/** @type {!Uint8Array} */ (result.value));\n } else if (!this.streamBinaryChunks_) {\n const dataPacket = result.value ?\n /** @type {!Uint8Array} */ (result.value) :\n new Uint8Array(0);\n const newText =\n 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_();\n } else {\n this.dispatchCallback_();\n }\n\n if (this.readyState == goog.net.FetchXmlHttp.RequestState.LOADING) {\n this.readInputFromFetch_();\n }\n};\n\n/**\n * Handles the response text.\n * @param {string} responseText\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseText_ = function(responseText) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = this.responseText = responseText;\n this.requestDone_();\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 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = responseArrayBuffer;\n this.requestDone_();\n};\n\n\n/**\n * Handles the send failure.\n * @param {*} error\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleSendFailure_ = function(error) {\n 'use strict';\n const 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_();\n};\n\n\n/**\n * Sets the request state to DONE and performs cleanup.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.requestDone_ = function() {\n 'use strict';\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 'use strict';\n this.requestHeaders_.append(header, value);\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getResponseHeader = function(header) {\n 'use strict';\n // TODO(user): This method should return null when the headers are not\n // present or the specified header is missing. The externs need to be fixed.\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get response header but no headers have been received ' +\n 'for url: ' + this.url_);\n return '';\n }\n return this.responseHeaders_.get(header.toLowerCase()) || '';\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getAllResponseHeaders = function() {\n 'use strict';\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 const lines = [];\n const iter = this.responseHeaders_.entries();\n let entry = iter.next();\n while (!entry.done) {\n const 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 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n/**\n * @return {!RequestCredentials|undefined} The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.getCredentialsMode = function() {\n 'use strict';\n return this.credentialsMode_;\n};\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\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 'use strict';\n if (this.onreadystatechange) {\n this.onreadystatechange.call(this);\n }\n};\n\n// Polyfill XmlHttpRequest's withCredentials property for specifying whether to\n// include credentials on cross domain requests.\nObject.defineProperty(goog.net.FetchXmlHttp.prototype, 'withCredentials', {\n get:\n /**\n * @this {goog.net.FetchXmlHttp}\n * @return {boolean} Whether to include credentials in cross domain\n * requests.\n */\n function() {\n 'use strict';\n return this.getCredentialsMode() === 'include';\n },\n\n set:\n /**\n * @param {boolean} value Whether to include credentials in cross domain\n * requests.\n * @this {goog.net.FetchXmlHttp}\n **/\n function(value) {\n 'use strict';\n this.setCredentialsMode(value ? 'include' : 'same-origin');\n }\n});\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Utility to attempt native JSON processing, falling back to\n * goog.json if not available.\n *\n * This is intended as a drop-in for current users of goog.json who want\n * to take advantage of native JSON if present.\n */\n\ngoog.provide('goog.json.hybrid');\n\ngoog.require('goog.asserts');\ngoog.require('goog.json');\n\n\n/**\n * Attempts to serialize the JSON string natively, falling back to\n * `goog.json.serialize` if unsuccessful.\n * @param {!Object} obj JavaScript object to serialize to JSON.\n * @return {string} Resulting JSON string.\n */\ngoog.json.hybrid.stringify = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['stringify'] :\n function(obj) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n return goog.global.JSON.stringify(obj);\n } catch (e) {\n // Native serialization failed. Fall through to retry with\n // goog.json.serialize.\n }\n }\n\n return goog.json.serialize(obj);\n };\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * the supplied `fallbackParser` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @param {function(string):Object} fallbackParser Fallback JSON parser used\n * if native\n * @return {?Object} Resulting JSON object.\n * @private\n */\ngoog.json.hybrid.parse_ = function(jsonString, fallbackParser) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n var obj = goog.global.JSON.parse(jsonString);\n goog.asserts.assert(typeof obj == 'object');\n return /** @type {?Object} */ (obj);\n } catch (e) {\n // Native parse failed. Fall through to retry with goog.json.parse.\n }\n }\n\n return fallbackParser(jsonString);\n};\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * `goog.json.parse` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @return {?Object} Resulting JSON object.\n */\ngoog.json.hybrid.parse = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['parse'] :\n function(jsonString) {\n 'use strict';\n return goog.json.hybrid.parse_(jsonString, goog.json.parse);\n };\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\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 CLIENT_CLOSED_REQUEST: 499, // Nonstandard, used by GRPC\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 'use strict';\n switch (status) {\n case goog.net.HttpStatus.OK:\n case goog.net.HttpStatus.CREATED:\n case goog.net.HttpStatus.ACCEPTED:\n case goog.net.HttpStatus.NO_CONTENT:\n case goog.net.HttpStatus.PARTIAL_CONTENT:\n case goog.net.HttpStatus.NOT_MODIFIED:\n case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:\n return true;\n\n default:\n return false;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides CORS support for HTTP based RPC requests.\n *\n * As part of net.rpc package, CORS features provided by this class\n * depend on the server support. Please check related specs to decide how\n * to enable any of the features provided by this class.\n */\n\ngoog.module('goog.net.rpc.HttpCors');\n\nconst GoogUri = goog.require('goog.Uri');\nconst googObject = goog.require('goog.object');\nconst googString = goog.require('goog.string');\nconst googUriUtils = goog.require('goog.uri.utils');\n\n\n/**\n * The default URL parameter name to overwrite http headers with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_HEADERS_PARAM_NAME = '$httpHeaders';\n\n\n/**\n * The default URL parameter name to overwrite http method with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_METHOD_PARAM_NAME = '$httpMethod';\n\n\n/**\n * Generates the URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateHttpHeadersOverwriteParam = function(headers) {\n let result = '';\n googObject.forEach(headers, function(value, key) {\n result += key;\n result += ':';\n result += value;\n result += '\\r\\n';\n });\n return result;\n};\n\n\n/**\n * Generates the URL-encoded URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateEncodedHttpHeadersOverwriteParam = function(headers) {\n return googString.urlEncode(\n exports.generateHttpHeadersOverwriteParam(headers));\n};\n\n\n/**\n * Sets custom HTTP headers via an overwrite URL param.\n *\n * @param {!GoogUri|string} url The URI object or a string path.\n * @param {string} urlParam The URL param name.\n * @param {!Object<string, string>} extraHeaders The HTTP headers.\n * @return {!GoogUri|string} The URI object or a string path with headers\n * encoded as a url param.\n */\nexports.setHttpHeadersWithOverwriteParam = function(\n url, urlParam, extraHeaders) {\n if (googObject.isEmpty(extraHeaders)) {\n return url;\n }\n const httpHeaders = exports.generateHttpHeadersOverwriteParam(extraHeaders);\n if (typeof url === 'string') {\n return googUriUtils.appendParam(\n url, googString.urlEncode(urlParam), httpHeaders);\n } else {\n url.setParameterValue(urlParam, httpHeaders); // duplicate removed!\n return url;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implementation of a WebChannel transport using WebChannelBase.\n *\n * When WebChannelBase is used as the underlying transport, the capabilities\n * of the WebChannel are limited to what's supported by the implementation.\n * Particularly, multiplexing is not possible, and only strings are\n * supported as message types.\n */\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBaseTransport');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.WebChannelBase');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.log');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.WebChannelTransport');\ngoog.require('goog.object');\ngoog.require('goog.string');\n\n\n\n/**\n * Implementation of {@link goog.net.WebChannelTransport} with\n * {@link goog.labs.net.webChannel.WebChannelBase} as the underlying channel\n * implementation.\n *\n * @constructor\n * @struct\n * @implements {goog.net.WebChannelTransport}\n * @final\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport = function() {\n 'use strict';\n if (!goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming()) {\n throw new Error('Environmental error: no available transport.');\n }\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannelBaseTransport =\n goog.labs.net.webChannel.WebChannelBaseTransport;\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.prototype.createWebChannel = function(\n url, opt_options) {\n 'use strict';\n return new WebChannelBaseTransport.Channel(url, opt_options);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel} interface.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance.\n *\n * @constructor\n * @implements {goog.net.WebChannel}\n * @extends {goog.events.EventTarget}\n * @final\n */\nWebChannelBaseTransport.Channel = function(url, opt_options) {\n 'use strict';\n WebChannelBaseTransport.Channel.base(this, 'constructor');\n\n /**\n * @private {!WebChannelBase} The underlying channel object.\n */\n this.channel_ = new WebChannelBase(\n opt_options, goog.net.WebChannelTransport.CLIENT_VERSION);\n\n /**\n * @private {string} The URL of the target server end-point.\n */\n this.url_ = url;\n\n /**\n * @private {goog.log.Logger} The logger for this class.\n */\n this.logger_ =\n goog.log.getLogger('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n /**\n * @private {Object<string, string>} Extra URL parameters\n * to be added to each HTTP request.\n */\n this.messageUrlParams_ =\n (opt_options && opt_options.messageUrlParams) || null;\n\n let messageHeaders = (opt_options && opt_options.messageHeaders) || null;\n\n // default is false\n if (opt_options && opt_options.clientProtocolHeaderRequired) {\n if (messageHeaders) {\n goog.object.set(\n messageHeaders, goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n } else {\n messageHeaders = goog.object.create(\n goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n }\n }\n\n this.channel_.setExtraHeaders(messageHeaders);\n\n let initHeaders = (opt_options && opt_options.initMessageHeaders) || null;\n\n if (opt_options && opt_options.messageContentType) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n }\n }\n\n if (opt_options && opt_options.clientProfile) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n }\n }\n\n this.channel_.setInitHeaders(initHeaders);\n\n const httpHeadersOverwriteParam =\n opt_options && opt_options.httpHeadersOverwriteParam;\n if (httpHeadersOverwriteParam &&\n !goog.string.isEmptyOrWhitespace(httpHeadersOverwriteParam)) {\n this.channel_.setHttpHeadersOverwriteParam(httpHeadersOverwriteParam);\n }\n\n /**\n * @private {boolean} Whether to enable CORS.\n */\n this.supportsCrossDomainXhr_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * @private {boolean} Whether to send raw Json and bypass v8 wire format.\n */\n this.sendRawJson_ = (opt_options && opt_options.sendRawJson) || false;\n\n // Note that httpSessionIdParam will be ignored if the same parameter name\n // has already been specified with messageUrlParams\n const httpSessionIdParam = opt_options && opt_options.httpSessionIdParam;\n if (httpSessionIdParam &&\n !goog.string.isEmptyOrWhitespace(httpSessionIdParam)) {\n this.channel_.setHttpSessionIdParam(httpSessionIdParam);\n if (goog.object.containsKey(this.messageUrlParams_, httpSessionIdParam)) {\n goog.object.remove(this.messageUrlParams_, httpSessionIdParam);\n goog.log.warning(\n this.logger_,\n 'Ignore httpSessionIdParam also specified with messageUrlParams: ' +\n httpSessionIdParam);\n }\n }\n\n /**\n * The channel handler.\n *\n * @private {!WebChannelBaseTransport.Channel.Handler_}\n */\n this.channelHandler_ = new WebChannelBaseTransport.Channel.Handler_(this);\n};\ngoog.inherits(WebChannelBaseTransport.Channel, goog.events.EventTarget);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.open = function() {\n 'use strict';\n this.channel_.setHandler(this.channelHandler_);\n if (this.supportsCrossDomainXhr_) {\n this.channel_.setSupportsCrossDomainXhrs(true);\n }\n this.channel_.connect(this.url_, (this.messageUrlParams_ || undefined));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.close = function() {\n 'use strict';\n this.channel_.disconnect();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.halfClose = function() {\n 'use strict';\n // to be implemented\n throw new Error('Not implemented');\n};\n\n\n/**\n * The WebChannelBase only supports object types.\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n *\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.send = function(message) {\n 'use strict';\n this.channel_.sendMap(this.messageToMapObject_(message));\n};\n\n\n/**\n * Converts a message to the map used by the underlying channel.\n *\n * @param {!goog.net.WebChannel.MessageData} message\n * @return {!Object|!goog.collections.maps.MapLike}\n */\nWebChannelBaseTransport.Channel.prototype.messageToMapObject_ = function(\n message) {\n 'use strict';\n goog.asserts.assert(\n goog.isObject(message) || typeof message === 'string',\n 'only object type or raw string is supported');\n\n if (typeof message === 'string') {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = message;\n return rawJson;\n }\n\n if (this.sendRawJson_) {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = goog.json.serialize(message);\n return rawJson;\n }\n\n return message;\n};\n\n\n/**\n * Converts the map used by the underlying channel to a message.\n *\n * NOTE: In the case of the message being JS Object or string, the exact same\n * object passed during `messageToMapObject_()` is returned. In the case of raw\n * JSON, an equal (but not the same) object is returned (due to serialization).\n *\n * @param {!Object|!goog.collections.maps.MapLike} map\n * @return {!goog.net.WebChannel.MessageData}\n */\nWebChannelBaseTransport.Channel.prototype.mapObjectToMessage_ = function(map) {\n 'use strict';\n if (Wire.RAW_DATA_KEY in map) {\n const rawMessage = map[Wire.RAW_DATA_KEY];\n\n if (this.sendRawJson_) {\n return /** @type {!goog.net.WebChannel.MessageData} */ (\n goog.json.parse(rawMessage));\n } else { // string message\n return rawMessage;\n }\n }\n\n return map;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.disposeInternal = function() {\n 'use strict';\n this.channel_.setHandler(null);\n delete this.channelHandler_;\n this.channel_.disconnect();\n delete this.channel_;\n\n WebChannelBaseTransport.Channel.base(this, 'disposeInternal');\n};\n\n\n\n/**\n * The message event.\n *\n * @param {!Array<?>|!Object} array The data array from the underlying channel.\n * @constructor\n * @extends {goog.net.WebChannel.MessageEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.MessageEvent = function(array) {\n 'use strict';\n WebChannelBaseTransport.Channel.MessageEvent.base(this, 'constructor');\n\n // Metadata as HTTP headers and status code (always come in a pair).\n if (array['__headers__']) {\n this.headers = array['__headers__'];\n this.statusCode = array['__status__'];\n delete array['__headers__'];\n delete array['__status__'];\n }\n\n // single-metadata only\n const metadata = array['__sm__'];\n if (metadata) {\n this.metadataKey = goog.object.getAnyKey(metadata);\n if (this.metadataKey) {\n this.data = goog.object.get(metadata, this.metadataKey);\n } else {\n this.data = metadata; // empty\n }\n } else {\n this.data = array;\n }\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.MessageEvent,\n goog.net.WebChannel.MessageEvent);\n\n\n\n/**\n * The error event.\n *\n * @param {WebChannelBase.Error} error The error code.\n * @constructor\n * @extends {goog.net.WebChannel.ErrorEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.ErrorEvent = function(error) {\n 'use strict';\n WebChannelBaseTransport.Channel.ErrorEvent.base(this, 'constructor');\n\n /**\n * High-level status code.\n */\n this.status = goog.net.WebChannel.ErrorStatus.NETWORK_ERROR;\n\n /**\n * @const {WebChannelBase.Error} Internal error code, for debugging use only.\n */\n this.errorCode = error;\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.ErrorEvent, goog.net.WebChannel.ErrorEvent);\n\n\n\n/**\n * Implementation of {@link WebChannelBase.Handler} interface.\n *\n * @param {!WebChannelBaseTransport.Channel} channel The enclosing WebChannel.\n *\n * @constructor\n * @extends {WebChannelBase.Handler}\n * @private\n */\nWebChannelBaseTransport.Channel.Handler_ = function(channel) {\n 'use strict';\n WebChannelBaseTransport.Channel.Handler_.base(this, 'constructor');\n\n /**\n * @type {!WebChannelBaseTransport.Channel}\n * @private\n */\n this.channel_ = channel;\n};\ngoog.inherits(WebChannelBaseTransport.Channel.Handler_, WebChannelBase.Handler);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelOpened = function(\n channel) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel opened on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.OPEN);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray =\n function(channel, array) {\n 'use strict';\n goog.asserts.assert(array, 'array expected to be defined');\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.MessageEvent(array));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelError = function(\n channel, error) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_,\n 'WebChannel aborted on ' + this.channel_.url_ +\n ' due to channel error: ' + error);\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.ErrorEvent(error));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel closed on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.CLOSE);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.getRuntimeProperties = function() {\n 'use strict';\n return new WebChannelBaseTransport.ChannelProperties(this, this.channel_);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel.RuntimeProperties}.\n *\n * @param {!WebChannelBaseTransport.Channel} transportChannel The transport\n * channel object.\n * @param {!WebChannelBase} channel The underlying channel object.\n *\n * @constructor\n * @implements {goog.net.WebChannel.RuntimeProperties}\n * @final\n */\nWebChannelBaseTransport.ChannelProperties = function(\n transportChannel, channel) {\n 'use strict';\n /**\n * The transport channel object.\n *\n * @private @const {!WebChannelBaseTransport.Channel}\n */\n this.transportChannel_ = transportChannel;\n\n /**\n * The underlying channel object.\n *\n * @private @const {!WebChannelBase}\n */\n this.channel_ = channel;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getConcurrentRequestLimit =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getMaxSize();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.isSpdyEnabled = function() {\n 'use strict';\n return this.getConcurrentRequestLimit() > 1;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getPendingRequestCount =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getRequestCount();\n};\n\n\n/**\n * @override\n * @return {!Array<!goog.net.WebChannel.MessageData>}\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getNonAckedMessages =\n function() {\n 'use strict';\n return this.channel_.getNonAckedMaps().map(\n queued_map => this.transportChannel_.mapObjectToMessage_(queued_map.map));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getHttpSessionId =\n function() {\n 'use strict';\n return this.channel_.getHttpSessionId();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.commit = function(\n callback) {\n 'use strict';\n this.channel_.setForwardChannelFlushCallback(callback);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.onCommit =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.ackCommit =\n goog.abstractMethod;\n\n\n/**\n * @override\n * @return {!Object<string, string>|undefined}\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getLastResponseHeaders =\n function() {\n 'use strict';\n return this.channel_.getLastResponseHeaders();\n};\n\n/** @override */\nWebChannelBaseTransport.ChannelProperties.prototype.getLastStatusCode =\n function() {\n 'use strict';\n return this.channel_.getLastStatusCode();\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview MD5 cryptographic hash.\n * Implementation of http://tools.ietf.org/html/rfc1321 with common\n * optimizations and tweaks (see http://en.wikipedia.org/wiki/MD5).\n *\n * Usage:\n * var md5 = new goog.crypt.Md5();\n * md5.update(bytes);\n * var hash = md5.digest();\n *\n * Performance:\n * Chrome 23 ~680 Mbit/s\n * Chrome 13 (in a VM) ~250 Mbit/s\n * Firefox 6.0 (in a VM) ~100 Mbit/s\n * IE9 (in a VM) ~27 Mbit/s\n * Firefox 3.6 ~15 Mbit/s\n * IE8 (in a VM) ~13 Mbit/s\n */\n\ngoog.provide('goog.crypt.Md5');\n\ngoog.require('goog.crypt.Hash');\n\n\n\n/**\n * MD5 cryptographic hash constructor.\n * @constructor\n * @extends {goog.crypt.Hash}\n * @final\n * @struct\n */\ngoog.crypt.Md5 = function() {\n 'use strict';\n goog.crypt.Md5.base(this, 'constructor');\n\n /** @const {number} */\n this.blockSize = 512 / 8;\n\n /**\n * Holds the current values of accumulated A-D variables (MD buffer).\n * @type {!Array<number>}\n * @private\n */\n this.chain_ = new Array(4);\n\n /**\n * A buffer holding the data until the whole block can be processed.\n * @type {!Array<number>}\n * @private\n */\n this.block_ = new Array(this.blockSize);\n\n /**\n * The length of yet-unprocessed data as collected in the block.\n * @type {number}\n * @private\n */\n this.blockLength_ = 0;\n\n /**\n * The total length of the message so far.\n * @type {number}\n * @private\n */\n this.totalLength_ = 0;\n\n this.reset();\n};\ngoog.inherits(goog.crypt.Md5, goog.crypt.Hash);\n\n\n/**\n * Integer rotation constants used by the abbreviated implementation.\n * They are hardcoded in the unrolled implementation, so it is left\n * here commented out.\n * @type {Array<number>}\n * @private\n *\ngoog.crypt.Md5.S_ = [\n 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21\n];\n */\n\n/**\n * Sine function constants used by the abbreviated implementation.\n * They are hardcoded in the unrolled implementation, so it is left\n * here commented out.\n * @type {Array<number>}\n * @private\n *\ngoog.crypt.Md5.T_ = [\n 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,\n 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,\n 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,\n 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,\n 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,\n 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,\n 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,\n 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,\n 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391\n];\n */\n\n\n/** @override */\ngoog.crypt.Md5.prototype.reset = function() {\n 'use strict';\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n\n this.blockLength_ = 0;\n this.totalLength_ = 0;\n};\n\n\n/**\n * Internal compress helper function. It takes a block of data (64 bytes)\n * and updates the accumulator.\n * @param {Array<number>|Uint8Array|string} buf The block to compress.\n * @param {number=} opt_offset Offset of the block in the buffer.\n * @private\n */\ngoog.crypt.Md5.prototype.compress_ = function(buf, opt_offset) {\n 'use strict';\n if (!opt_offset) {\n opt_offset = 0;\n }\n\n // We allocate the array every time, but it's cheap in practice.\n var X = new Array(16);\n\n // Get 16 little endian words. It is not worth unrolling this for Chrome 11.\n if (typeof buf === 'string') {\n for (var i = 0; i < 16; ++i) {\n X[i] = (buf.charCodeAt(opt_offset++)) |\n (buf.charCodeAt(opt_offset++) << 8) |\n (buf.charCodeAt(opt_offset++) << 16) |\n (buf.charCodeAt(opt_offset++) << 24);\n }\n } else {\n for (var i = 0; i < 16; ++i) {\n X[i] = (buf[opt_offset++]) | (buf[opt_offset++] << 8) |\n (buf[opt_offset++] << 16) | (buf[opt_offset++] << 24);\n }\n }\n\n var A = this.chain_[0];\n var B = this.chain_[1];\n var C = this.chain_[2];\n var D = this.chain_[3];\n var sum = 0;\n\n /*\n * This is an abbreviated implementation, it is left here commented out for\n * reference purposes. See below for an unrolled version in use.\n *\n var f, n, tmp;\n for (var i = 0; i < 64; ++i) {\n\n if (i < 16) {\n f = (D ^ (B & (C ^ D)));\n n = i;\n } else if (i < 32) {\n f = (C ^ (D & (B ^ C)));\n n = (5 * i + 1) % 16;\n } else if (i < 48) {\n f = (B ^ C ^ D);\n n = (3 * i + 5) % 16;\n } else {\n f = (C ^ (B | (~D)));\n n = (7 * i) % 16;\n }\n\n tmp = D;\n D = C;\n C = B;\n sum = (A + f + goog.crypt.Md5.T_[i] + X[n]) & 0xffffffff;\n B += ((sum << goog.crypt.Md5.S_[i]) & 0xffffffff) |\n (sum >>> (32 - goog.crypt.Md5.S_[i]));\n A = tmp;\n }\n */\n\n /*\n * This is an unrolled MD5 implementation, which gives ~30% speedup compared\n * to the abbreviated implementation above, as measured on Chrome 11. It is\n * important to keep 32-bit croppings to minimum and inline the integer\n * rotation.\n */\n sum = (A + (D ^ (B & (C ^ D))) + X[0] + 0xd76aa478) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[1] + 0xe8c7b756) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[2] + 0x242070db) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[3] + 0xc1bdceee) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[4] + 0xf57c0faf) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[5] + 0x4787c62a) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[6] + 0xa8304613) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[7] + 0xfd469501) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[8] + 0x698098d8) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[9] + 0x8b44f7af) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[10] + 0xffff5bb1) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[11] + 0x895cd7be) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (D ^ (B & (C ^ D))) + X[12] + 0x6b901122) & 0xffffffff;\n A = B + (((sum << 7) & 0xffffffff) | (sum >>> 25));\n sum = (D + (C ^ (A & (B ^ C))) + X[13] + 0xfd987193) & 0xffffffff;\n D = A + (((sum << 12) & 0xffffffff) | (sum >>> 20));\n sum = (C + (B ^ (D & (A ^ B))) + X[14] + 0xa679438e) & 0xffffffff;\n C = D + (((sum << 17) & 0xffffffff) | (sum >>> 15));\n sum = (B + (A ^ (C & (D ^ A))) + X[15] + 0x49b40821) & 0xffffffff;\n B = C + (((sum << 22) & 0xffffffff) | (sum >>> 10));\n sum = (A + (C ^ (D & (B ^ C))) + X[1] + 0xf61e2562) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[6] + 0xc040b340) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[11] + 0x265e5a51) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[0] + 0xe9b6c7aa) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[5] + 0xd62f105d) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[10] + 0x02441453) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[15] + 0xd8a1e681) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[4] + 0xe7d3fbc8) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[9] + 0x21e1cde6) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[14] + 0xc33707d6) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[3] + 0xf4d50d87) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[8] + 0x455a14ed) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (C ^ (D & (B ^ C))) + X[13] + 0xa9e3e905) & 0xffffffff;\n A = B + (((sum << 5) & 0xffffffff) | (sum >>> 27));\n sum = (D + (B ^ (C & (A ^ B))) + X[2] + 0xfcefa3f8) & 0xffffffff;\n D = A + (((sum << 9) & 0xffffffff) | (sum >>> 23));\n sum = (C + (A ^ (B & (D ^ A))) + X[7] + 0x676f02d9) & 0xffffffff;\n C = D + (((sum << 14) & 0xffffffff) | (sum >>> 18));\n sum = (B + (D ^ (A & (C ^ D))) + X[12] + 0x8d2a4c8a) & 0xffffffff;\n B = C + (((sum << 20) & 0xffffffff) | (sum >>> 12));\n sum = (A + (B ^ C ^ D) + X[5] + 0xfffa3942) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[8] + 0x8771f681) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[11] + 0x6d9d6122) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[14] + 0xfde5380c) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[1] + 0xa4beea44) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[4] + 0x4bdecfa9) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[7] + 0xf6bb4b60) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[10] + 0xbebfbc70) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[13] + 0x289b7ec6) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[0] + 0xeaa127fa) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[3] + 0xd4ef3085) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[6] + 0x04881d05) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (B ^ C ^ D) + X[9] + 0xd9d4d039) & 0xffffffff;\n A = B + (((sum << 4) & 0xffffffff) | (sum >>> 28));\n sum = (D + (A ^ B ^ C) + X[12] + 0xe6db99e5) & 0xffffffff;\n D = A + (((sum << 11) & 0xffffffff) | (sum >>> 21));\n sum = (C + (D ^ A ^ B) + X[15] + 0x1fa27cf8) & 0xffffffff;\n C = D + (((sum << 16) & 0xffffffff) | (sum >>> 16));\n sum = (B + (C ^ D ^ A) + X[2] + 0xc4ac5665) & 0xffffffff;\n B = C + (((sum << 23) & 0xffffffff) | (sum >>> 9));\n sum = (A + (C ^ (B | (~D))) + X[0] + 0xf4292244) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[7] + 0x432aff97) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[14] + 0xab9423a7) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[5] + 0xfc93a039) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[12] + 0x655b59c3) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[3] + 0x8f0ccc92) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[10] + 0xffeff47d) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[1] + 0x85845dd1) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[8] + 0x6fa87e4f) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[15] + 0xfe2ce6e0) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[6] + 0xa3014314) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[13] + 0x4e0811a1) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\n sum = (A + (C ^ (B | (~D))) + X[4] + 0xf7537e82) & 0xffffffff;\n A = B + (((sum << 6) & 0xffffffff) | (sum >>> 26));\n sum = (D + (B ^ (A | (~C))) + X[11] + 0xbd3af235) & 0xffffffff;\n D = A + (((sum << 10) & 0xffffffff) | (sum >>> 22));\n sum = (C + (A ^ (D | (~B))) + X[2] + 0x2ad7d2bb) & 0xffffffff;\n C = D + (((sum << 15) & 0xffffffff) | (sum >>> 17));\n sum = (B + (D ^ (C | (~A))) + X[9] + 0xeb86d391) & 0xffffffff;\n B = C + (((sum << 21) & 0xffffffff) | (sum >>> 11));\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};\n\n\n/** @override */\ngoog.crypt.Md5.prototype.update = function(bytes, opt_length) {\n 'use strict';\n if (opt_length === undefined) {\n opt_length = bytes.length;\n }\n var lengthMinusBlock = opt_length - this.blockSize;\n\n // Copy some object properties to local variables in order to save on access\n // time from inside the loop (~10% speedup was observed on Chrome 11).\n var block = this.block_;\n var blockLength = this.blockLength_;\n var i = 0;\n\n // The outer while loop should execute at most twice.\n while (i < opt_length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~30%\n // speedup on Chrome 14 and ~70% speedup on Firefox 6.0, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (blockLength == 0) {\n while (i <= lengthMinusBlock) {\n this.compress_(bytes, i);\n i += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (i < opt_length) {\n block[blockLength++] = bytes.charCodeAt(i++);\n if (blockLength == this.blockSize) {\n this.compress_(block);\n blockLength = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (i < opt_length) {\n block[blockLength++] = bytes[i++];\n if (blockLength == this.blockSize) {\n this.compress_(block);\n blockLength = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.blockLength_ = blockLength;\n this.totalLength_ += opt_length;\n};\n\n\n/** @override */\ngoog.crypt.Md5.prototype.digest = function() {\n 'use strict';\n // This must accommodate at least 1 padding byte (0x80), 8 bytes of\n // total bitlength, and must end at a 64-byte boundary.\n var pad = new Array(\n (this.blockLength_ < 56 ? this.blockSize : this.blockSize * 2) -\n this.blockLength_);\n\n // Add padding: 0x80 0x00*\n pad[0] = 0x80;\n for (var i = 1; i < pad.length - 8; ++i) {\n pad[i] = 0;\n }\n // Add the total number of bits, little endian 64-bit integer.\n var totalBits = this.totalLength_ * 8;\n for (var i = pad.length - 8; i < pad.length; ++i) {\n pad[i] = totalBits & 0xff;\n totalBits /= 0x100; // Don't use bit-shifting here!\n }\n this.update(pad);\n\n var digest = new Array(16);\n var n = 0;\n for (var i = 0; i < 4; ++i) {\n for (var j = 0; j < 32; j += 8) {\n digest[n++] = (this.chain_[i] >>> j) & 0xff;\n }\n }\n return digest;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Abstract cryptographic hash interface.\n *\n * See goog.crypt.Sha1 and goog.crypt.Md5 for sample implementations.\n */\n\ngoog.provide('goog.crypt.Hash');\n\n\n\n/**\n * Create a cryptographic hash instance.\n *\n * @constructor\n * @struct\n */\ngoog.crypt.Hash = function() {\n 'use strict';\n /**\n * The block size for the hasher.\n * @type {number}\n */\n this.blockSize = -1;\n};\n\n\n/**\n * Resets the internal accumulator.\n */\ngoog.crypt.Hash.prototype.reset = goog.abstractMethod;\n\n\n/**\n * Adds a byte array (array with values in [0-255] range) or a string (must\n * only contain 8-bit, i.e., Latin1 characters) to the internal accumulator.\n *\n * Many hash functions operate on blocks of data and implement optimizations\n * when a full chunk of data is readily available. Hence it is often preferable\n * to provide large chunks of data (a kilobyte or more) than to repeatedly\n * call the update method with few tens of bytes. If this is not possible, or\n * not feasible, it might be good to provide data in multiplies of hash block\n * size (often 64 bytes). Please see the implementation and performance tests\n * of your favourite hash.\n *\n * @param {Array<number>|Uint8Array|string} bytes Data used for the update.\n * @param {number=} opt_length Number of bytes to use.\n */\ngoog.crypt.Hash.prototype.update = goog.abstractMethod;\n\n\n/**\n * @return {!Array<number>} The finalized hash computed\n * from the internal accumulator.\n */\ngoog.crypt.Hash.prototype.digest = goog.abstractMethod;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Defines an Integer class for representing (potentially)\n * infinite length two's-complement integer values.\n *\n * For the specific case of 64-bit integers, use goog.math.Long, which is more\n * efficient.\n */\n\ngoog.provide('goog.math.Integer');\n\ngoog.require('goog.reflect');\n\n/**\n * Constructs a two's-complement integer an array containing bits of the\n * integer in 32-bit (signed) pieces, given in little-endian order (i.e.,\n * lowest-order bits in the first piece), and the sign of -1 or 0.\n *\n * See the from* functions below for other convenient ways of constructing\n * Integers.\n *\n * The internal representation of an integer is an array of 32-bit signed\n * pieces, along with a sign (0 or -1) that indicates the contents of all the\n * other 32-bit pieces out to infinity. We use 32-bit pieces because these are\n * the size of integers on which JavaScript performs bit-operations. For\n * operations like addition and multiplication, we split each number into 16-bit\n * pieces, which can easily be multiplied within JavaScript's floating-point\n * representation without overflow or change in sign.\n *\n * @struct\n * @constructor\n * @param {Array<number>} bits Array containing the bits of the number.\n * @param {number} sign The sign of the number: -1 for negative and 0 positive.\n * @final\n */\ngoog.math.Integer = function(bits, sign) {\n 'use strict';\n /**\n * @type {number}\n * @private\n */\n this.sign_ = sign;\n\n // Note: using a local variable while initializing the array helps the\n // compiler understand that assigning to the array is local side-effect and\n // that enables the entire constructor to be seen as side-effect free.\n var localBits = [];\n\n // Copy the 32-bit signed integer values passed in. We prune out those at the\n // top that equal the sign since they are redundant.\n var top = true;\n\n for (var i = bits.length - 1; i >= 0; i--) {\n var val = bits[i] | 0;\n if (!top || val != sign) {\n localBits[i] = val;\n top = false;\n }\n }\n\n /**\n * @type {!Array<number>}\n * @private\n * @const\n */\n this.bits_ = localBits;\n};\n\n\n// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the\n// from* methods on which they depend.\n\n\n/**\n * A cache of the Integer representations of small integer values.\n * @type {!Object<number, !goog.math.Integer>}\n * @private\n */\ngoog.math.Integer.IntCache_ = {};\n\n\n/**\n * Returns an Integer representing the given (32-bit) integer value.\n * @param {number} value A 32-bit integer value.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromInt = function(value) {\n 'use strict';\n if (-128 <= value && value < 128) {\n return goog.reflect.cache(\n goog.math.Integer.IntCache_, value, function(val) {\n 'use strict';\n return new goog.math.Integer([val | 0], val < 0 ? -1 : 0);\n });\n }\n return new goog.math.Integer([value | 0], value < 0 ? -1 : 0);\n};\n\n\n/**\n * Returns an Integer representing the given value, provided that it is a finite\n * number. Otherwise, zero is returned.\n * @param {number} value The value in question.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromNumber = function(value) {\n 'use strict';\n if (isNaN(value) || !isFinite(value)) {\n return goog.math.Integer.ZERO;\n } else if (value < 0) {\n return goog.math.Integer.fromNumber(-value).negate();\n } else {\n var bits = [];\n var pow = 1;\n for (var i = 0; value >= pow; i++) {\n bits[i] = (value / pow) | 0;\n pow *= goog.math.Integer.TWO_PWR_32_DBL_;\n }\n return new goog.math.Integer(bits, 0);\n }\n};\n\n\n/**\n * Returns a Integer representing the value that comes by concatenating the\n * given entries, each is assumed to be 32 signed bits, given in little-endian\n * order (lowest order bits in the lowest index), and sign-extending the highest\n * order 32-bit value.\n * @param {Array<number>} bits The bits of the number, in 32-bit signed pieces,\n * in little-endian order.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromBits = function(bits) {\n 'use strict';\n var high = bits[bits.length - 1];\n return new goog.math.Integer(bits, high & (1 << 31) ? -1 : 0);\n};\n\n\n/**\n * Returns an Integer representation of the given string, written using the\n * given radix.\n * @param {string} str The textual representation of the Integer.\n * @param {number=} opt_radix The radix in which the text is written.\n * @return {!goog.math.Integer} The corresponding Integer value.\n */\ngoog.math.Integer.fromString = function(str, opt_radix) {\n 'use strict';\n if (str.length == 0) {\n throw new Error('number format error: empty string');\n }\n\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw new Error('radix out of range: ' + radix);\n }\n\n if (str.charAt(0) == '-') {\n return goog.math.Integer.fromString(str.substring(1), radix).negate();\n } else if (str.indexOf('-') >= 0) {\n throw new Error('number format error: interior \"-\" character');\n }\n\n // Do several (8) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 8));\n\n var result = goog.math.Integer.ZERO;\n for (var i = 0; i < str.length; i += 8) {\n var size = Math.min(8, str.length - i);\n var value = parseInt(str.substring(i, i + size), radix);\n if (size < 8) {\n var power = goog.math.Integer.fromNumber(Math.pow(radix, size));\n result = result.multiply(power).add(goog.math.Integer.fromNumber(value));\n } else {\n result = result.multiply(radixToPower);\n result = result.add(goog.math.Integer.fromNumber(value));\n }\n }\n return result;\n};\n\n\n/**\n * A number used repeatedly in calculations. This must appear before the first\n * call to the from* functions below.\n * @type {number}\n * @private\n */\ngoog.math.Integer.TWO_PWR_32_DBL_ = (1 << 16) * (1 << 16);\n\n\n/** @type {!goog.math.Integer} */\ngoog.math.Integer.ZERO = goog.math.Integer.fromInt(0);\n\n/** @type {!goog.math.Integer} */\ngoog.math.Integer.ONE = goog.math.Integer.fromInt(1);\n\n\n/**\n * @const\n * @type {!goog.math.Integer}\n * @private\n */\ngoog.math.Integer.TWO_PWR_24_ = goog.math.Integer.fromInt(1 << 24);\n\n/**\n * Returns the value, assuming it is a 32-bit integer.\n * @return {number} The corresponding int value.\n */\ngoog.math.Integer.prototype.toInt = function() {\n 'use strict';\n return this.bits_.length > 0 ? this.bits_[0] : this.sign_;\n};\n\n\n/** @return {number} The closest floating-point representation to this value. */\ngoog.math.Integer.prototype.toNumber = function() {\n 'use strict';\n if (this.isNegative()) {\n return -this.negate().toNumber();\n } else {\n var val = 0;\n var pow = 1;\n for (var i = 0; i < this.bits_.length; i++) {\n val += this.getBitsUnsigned(i) * pow;\n pow *= goog.math.Integer.TWO_PWR_32_DBL_;\n }\n return val;\n }\n};\n\n\n/**\n * @param {number=} opt_radix The radix in which the text should be written.\n * @return {string} The textual representation of this value.\n * @override\n */\ngoog.math.Integer.prototype.toString = function(opt_radix) {\n 'use strict';\n var radix = opt_radix || 10;\n if (radix < 2 || 36 < radix) {\n throw new Error('radix out of range: ' + radix);\n }\n\n if (this.isZero()) {\n return '0';\n } else if (this.isNegative()) {\n return '-' + this.negate().toString(radix);\n }\n\n // Do several (6) digits each time through the loop, so as to\n // minimize the calls to the very expensive emulated div.\n var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 6));\n\n var rem = this;\n var result = '';\n while (true) {\n var remDiv = rem.divide(radixToPower);\n // The right shifting fixes negative values in the case when\n // intval >= 2^31; for more details see\n // https://github.com/google/closure-library/pull/498\n var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0;\n var digits = intval.toString(radix);\n\n rem = remDiv;\n if (rem.isZero()) {\n return digits + result;\n } else {\n while (digits.length < 6) {\n digits = '0' + digits;\n }\n result = '' + digits + result;\n }\n }\n};\n\n\n/**\n * Returns the index-th 32-bit (signed) piece of the Integer according to\n * little-endian order (i.e., index 0 contains the smallest bits).\n * @param {number} index The index in question.\n * @return {number} The requested 32-bits as a signed number.\n */\ngoog.math.Integer.prototype.getBits = function(index) {\n 'use strict';\n if (index < 0) {\n return 0; // Allowing this simplifies bit shifting operations below...\n } else if (index < this.bits_.length) {\n return this.bits_[index];\n } else {\n return this.sign_;\n }\n};\n\n\n/**\n * Returns the index-th 32-bit piece as an unsigned number.\n * @param {number} index The index in question.\n * @return {number} The requested 32-bits as an unsigned number.\n */\ngoog.math.Integer.prototype.getBitsUnsigned = function(index) {\n 'use strict';\n var val = this.getBits(index);\n return val >= 0 ? val : goog.math.Integer.TWO_PWR_32_DBL_ + val;\n};\n\n\n/** @return {number} The sign bit of this number, -1 or 0. */\ngoog.math.Integer.prototype.getSign = function() {\n 'use strict';\n return this.sign_;\n};\n\n\n/** @return {boolean} Whether this value is zero. */\ngoog.math.Integer.prototype.isZero = function() {\n 'use strict';\n if (this.sign_ != 0) {\n return false;\n }\n for (var i = 0; i < this.bits_.length; i++) {\n if (this.bits_[i] != 0) {\n return false;\n }\n }\n return true;\n};\n\n\n/** @return {boolean} Whether this value is negative. */\ngoog.math.Integer.prototype.isNegative = function() {\n 'use strict';\n return this.sign_ == -1;\n};\n\n\n/** @return {boolean} Whether this value is odd. */\ngoog.math.Integer.prototype.isOdd = function() {\n 'use strict';\n return (this.bits_.length == 0) && (this.sign_ == -1) ||\n (this.bits_.length > 0) && ((this.bits_[0] & 1) != 0);\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer equals the other.\n */\ngoog.math.Integer.prototype.equals = function(other) {\n 'use strict';\n if (this.sign_ != other.sign_) {\n return false;\n }\n var len = Math.max(this.bits_.length, other.bits_.length);\n for (var i = 0; i < len; i++) {\n if (this.getBits(i) != other.getBits(i)) {\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer does not equal the other.\n */\ngoog.math.Integer.prototype.notEquals = function(other) {\n 'use strict';\n return !this.equals(other);\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is greater than the other.\n */\ngoog.math.Integer.prototype.greaterThan = function(other) {\n 'use strict';\n return this.compare(other) > 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is greater than or equal to the other.\n */\ngoog.math.Integer.prototype.greaterThanOrEqual = function(other) {\n 'use strict';\n return this.compare(other) >= 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is less than the other.\n */\ngoog.math.Integer.prototype.lessThan = function(other) {\n 'use strict';\n return this.compare(other) < 0;\n};\n\n\n/**\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {boolean} Whether this Integer is less than or equal to the other.\n */\ngoog.math.Integer.prototype.lessThanOrEqual = function(other) {\n 'use strict';\n return this.compare(other) <= 0;\n};\n\n\n/**\n * Compares this Integer with the given one.\n * @param {goog.math.Integer} other Integer to compare against.\n * @return {number} 0 if they are the same, 1 if the this is greater, and -1\n * if the given one is greater.\n */\ngoog.math.Integer.prototype.compare = function(other) {\n 'use strict';\n var diff = this.subtract(other);\n if (diff.isNegative()) {\n return -1;\n } else if (diff.isZero()) {\n return 0;\n } else {\n return +1;\n }\n};\n\n\n/**\n * Returns an integer with only the first numBits bits of this value, sign\n * extended from the final bit.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} The shorted integer value.\n */\ngoog.math.Integer.prototype.shorten = function(numBits) {\n 'use strict';\n var arr_index = (numBits - 1) >> 5;\n var bit_index = (numBits - 1) % 32;\n var bits = [];\n for (var i = 0; i < arr_index; i++) {\n bits[i] = this.getBits(i);\n }\n var sigBits = bit_index == 31 ? 0xFFFFFFFF : (1 << (bit_index + 1)) - 1;\n var val = this.getBits(arr_index) & sigBits;\n if (val & (1 << bit_index)) {\n val |= 0xFFFFFFFF - sigBits;\n bits[arr_index] = val;\n return new goog.math.Integer(bits, -1);\n } else {\n bits[arr_index] = val;\n return new goog.math.Integer(bits, 0);\n }\n};\n\n\n/** @return {!goog.math.Integer} The negation of this value. */\ngoog.math.Integer.prototype.negate = function() {\n 'use strict';\n return this.not().add(goog.math.Integer.ONE);\n};\n\n\n/** @return {!goog.math.Integer} The absolute value of this value. */\ngoog.math.Integer.prototype.abs = function() {\n 'use strict';\n return this.isNegative() ? this.negate() : this;\n};\n\n\n/**\n * Returns the sum of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to add to this.\n * @return {!goog.math.Integer} The Integer result.\n */\ngoog.math.Integer.prototype.add = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n var carry = 0;\n\n for (var i = 0; i <= len; i++) {\n var a1 = this.getBits(i) >>> 16;\n var a0 = this.getBits(i) & 0xFFFF;\n\n var b1 = other.getBits(i) >>> 16;\n var b0 = other.getBits(i) & 0xFFFF;\n\n var c0 = carry + a0 + b0;\n var c1 = (c0 >>> 16) + a1 + b1;\n carry = c1 >>> 16;\n c0 &= 0xFFFF;\n c1 &= 0xFFFF;\n arr[i] = (c1 << 16) | c0;\n }\n return goog.math.Integer.fromBits(arr);\n};\n\n\n/**\n * Returns the difference of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to subtract from this.\n * @return {!goog.math.Integer} The Integer result.\n */\ngoog.math.Integer.prototype.subtract = function(other) {\n 'use strict';\n return this.add(other.negate());\n};\n\n\n/**\n * Returns the product of this and the given Integer.\n * @param {goog.math.Integer} other The Integer to multiply against this.\n * @return {!goog.math.Integer} The product of this and the other.\n */\ngoog.math.Integer.prototype.multiply = function(other) {\n 'use strict';\n if (this.isZero()) {\n return goog.math.Integer.ZERO;\n } else if (other.isZero()) {\n return goog.math.Integer.ZERO;\n }\n\n if (this.isNegative()) {\n if (other.isNegative()) {\n return this.negate().multiply(other.negate());\n } else {\n return this.negate().multiply(other).negate();\n }\n } else if (other.isNegative()) {\n return this.multiply(other.negate()).negate();\n }\n\n // If both numbers are small, use float multiplication\n if (this.lessThan(goog.math.Integer.TWO_PWR_24_) &&\n other.lessThan(goog.math.Integer.TWO_PWR_24_)) {\n return goog.math.Integer.fromNumber(this.toNumber() * other.toNumber());\n }\n\n // Fill in an array of 16-bit products.\n var len = this.bits_.length + other.bits_.length;\n var arr = [];\n for (var i = 0; i < 2 * len; i++) {\n arr[i] = 0;\n }\n for (var i = 0; i < this.bits_.length; i++) {\n for (var j = 0; j < other.bits_.length; j++) {\n var a1 = this.getBits(i) >>> 16;\n var a0 = this.getBits(i) & 0xFFFF;\n\n var b1 = other.getBits(j) >>> 16;\n var b0 = other.getBits(j) & 0xFFFF;\n\n arr[2 * i + 2 * j] += a0 * b0;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j);\n arr[2 * i + 2 * j + 1] += a1 * b0;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);\n arr[2 * i + 2 * j + 1] += a0 * b1;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);\n arr[2 * i + 2 * j + 2] += a1 * b1;\n goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 2);\n }\n }\n\n // Combine the 16-bit values into 32-bit values.\n for (var i = 0; i < len; i++) {\n arr[i] = (arr[2 * i + 1] << 16) | arr[2 * i];\n }\n for (var i = len; i < 2 * len; i++) {\n arr[i] = 0;\n }\n return new goog.math.Integer(arr, 0);\n};\n\n\n/**\n * Carries any overflow from the given index into later entries.\n * @param {Array<number>} bits Array of 16-bit values in little-endian order.\n * @param {number} index The index in question.\n * @private\n */\ngoog.math.Integer.carry16_ = function(bits, index) {\n 'use strict';\n while ((bits[index] & 0xFFFF) != bits[index]) {\n bits[index + 1] += bits[index] >>> 16;\n bits[index] &= 0xFFFF;\n index++;\n }\n};\n\n\n/**\n * Returns \"this\" Integer divided by the given one. Both \"this\" and the given\n * Integer MUST be positive.\n *\n * This method is only needed for very large numbers (>10^308),\n * for which the original division algorithm gets into an infinite\n * loop (see https://github.com/google/closure-library/issues/500).\n *\n * The algorithm has some possible performance enhancements (or\n * could be rewritten entirely), it's just an initial solution for\n * the issue linked above.\n *\n * @param {!goog.math.Integer} other The Integer to divide \"this\" by.\n * @return {!goog.math.Integer.DivisionResult}\n * @private\n */\ngoog.math.Integer.prototype.slowDivide_ = function(other) {\n 'use strict';\n if (this.isNegative() || other.isNegative()) {\n throw new Error('slowDivide_ only works with positive integers.');\n }\n\n var twoPower = goog.math.Integer.ONE;\n var multiple = other;\n\n // First we have to figure out what the highest bit of the result\n // is, so we increase \"twoPower\" and \"multiple\" until \"multiple\"\n // exceeds \"this\".\n while (multiple.lessThanOrEqual(this)) {\n twoPower = twoPower.shiftLeft(1);\n multiple = multiple.shiftLeft(1);\n }\n\n // Rewind by one power of two, giving us the highest bit of the\n // result.\n var res = twoPower.shiftRight(1);\n var total = multiple.shiftRight(1);\n\n // Now we starting decreasing \"multiple\" and \"twoPower\" to find the\n // rest of the bits of the result.\n var total2;\n multiple = multiple.shiftRight(2);\n twoPower = twoPower.shiftRight(2);\n while (!multiple.isZero()) {\n // whenever we can add \"multiple\" to the total and not exceed\n // \"this\", that means we've found a 1 bit. Else we've found a 0\n // and don't need to add to the result.\n total2 = total.add(multiple);\n if (total2.lessThanOrEqual(this)) {\n res = res.add(twoPower);\n total = total2;\n }\n multiple = multiple.shiftRight(1);\n twoPower = twoPower.shiftRight(1);\n }\n\n\n // TODO(user): Calculate this more efficiently during the division.\n // This is kind of a waste since it isn't always needed, but it keeps the\n // API smooth. Since this is already a slow path it probably isn't a big deal.\n var remainder = this.subtract(res.multiply(other));\n return new goog.math.Integer.DivisionResult(res, remainder);\n};\n\n\n/**\n * Returns this Integer divided by the given one.\n * @param {!goog.math.Integer} other The Integer to divide this by.\n * @return {!goog.math.Integer} This value divided by the given one.\n */\ngoog.math.Integer.prototype.divide = function(other) {\n 'use strict';\n return this.divideAndRemainder(other).quotient;\n};\n\n\n/**\n * A struct for holding the quotient and remainder of a division.\n *\n * @constructor\n * @final\n * @struct\n *\n * @param {!goog.math.Integer} quotient\n * @param {!goog.math.Integer} remainder\n */\ngoog.math.Integer.DivisionResult = function(quotient, remainder) {\n 'use strict';\n /** @const */\n this.quotient = quotient;\n\n /** @const */\n this.remainder = remainder;\n};\n\n\n/**\n * Returns this Integer divided by the given one, as well as the remainder of\n * that division.\n *\n * @param {!goog.math.Integer} other The Integer to divide this by.\n * @return {!goog.math.Integer.DivisionResult}\n */\ngoog.math.Integer.prototype.divideAndRemainder = function(other) {\n 'use strict';\n if (other.isZero()) {\n throw new Error('division by zero');\n } else if (this.isZero()) {\n return new goog.math.Integer.DivisionResult(\n goog.math.Integer.ZERO, goog.math.Integer.ZERO);\n }\n\n if (this.isNegative()) {\n // Do the division on the negative of the numerator...\n var result = this.negate().divideAndRemainder(other);\n return new goog.math.Integer.DivisionResult(\n // ...and flip the sign back after.\n result.quotient.negate(),\n // The remainder must always have the same sign as the numerator.\n result.remainder.negate());\n } else if (other.isNegative()) {\n // Do the division on the negative of the denominator...\n var result = this.divideAndRemainder(other.negate());\n return new goog.math.Integer.DivisionResult(\n // ...and flip the sign back after.\n result.quotient.negate(),\n // The remainder must always have the same sign as the numerator.\n result.remainder);\n }\n\n // Have to degrade to slowDivide for Very Large Numbers, because\n // they're out of range for the floating-point approximation\n // technique used below.\n if (this.bits_.length > 30) {\n return this.slowDivide_(other);\n }\n\n // Repeat the following until the remainder is less than other: find a\n // floating-point that approximates remainder / other *from below*, add this\n // into the result, and subtract it from the remainder. It is critical that\n // the approximate value is less than or equal to the real value so that the\n // remainder never becomes negative.\n var res = goog.math.Integer.ZERO;\n var rem = this;\n while (rem.greaterThanOrEqual(other)) {\n // Approximate the result of division. This may be a little greater or\n // smaller than the actual value.\n var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));\n\n // We will tweak the approximate result by changing it in the 48-th digit or\n // the smallest non-fractional digit, whichever is larger.\n var log2 = Math.ceil(Math.log(approx) / Math.LN2);\n var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);\n\n // Decrease the approximation until it is smaller than the remainder. Note\n // that if it is too large, the product overflows and is negative.\n var approxRes = goog.math.Integer.fromNumber(approx);\n var approxRem = approxRes.multiply(other);\n while (approxRem.isNegative() || approxRem.greaterThan(rem)) {\n approx -= delta;\n approxRes = goog.math.Integer.fromNumber(approx);\n approxRem = approxRes.multiply(other);\n }\n\n // We know the answer can't be zero... and actually, zero would cause\n // infinite recursion since we would make no progress.\n if (approxRes.isZero()) {\n approxRes = goog.math.Integer.ONE;\n }\n\n res = res.add(approxRes);\n rem = rem.subtract(approxRem);\n }\n return new goog.math.Integer.DivisionResult(res, rem);\n};\n\n\n/**\n * Returns this Integer modulo the given one.\n * @param {!goog.math.Integer} other The Integer by which to mod.\n * @return {!goog.math.Integer} This value modulo the given one.\n */\ngoog.math.Integer.prototype.modulo = function(other) {\n 'use strict';\n return this.divideAndRemainder(other).remainder;\n};\n\n\n/** @return {!goog.math.Integer} The bitwise-NOT of this value. */\ngoog.math.Integer.prototype.not = function() {\n 'use strict';\n var len = this.bits_.length;\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = ~this.bits_[i];\n }\n return new goog.math.Integer(arr, ~this.sign_);\n};\n\n\n/**\n * Returns the bitwise-AND of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to AND with this.\n * @return {!goog.math.Integer} The bitwise-AND of this and the other.\n */\ngoog.math.Integer.prototype.and = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) & other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ & other.sign_);\n};\n\n\n/**\n * Returns the bitwise-OR of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to OR with this.\n * @return {!goog.math.Integer} The bitwise-OR of this and the other.\n */\ngoog.math.Integer.prototype.or = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) | other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ | other.sign_);\n};\n\n\n/**\n * Returns the bitwise-XOR of this Integer and the given one.\n * @param {goog.math.Integer} other The Integer to XOR with this.\n * @return {!goog.math.Integer} The bitwise-XOR of this and the other.\n */\ngoog.math.Integer.prototype.xor = function(other) {\n 'use strict';\n var len = Math.max(this.bits_.length, other.bits_.length);\n var arr = [];\n for (var i = 0; i < len; i++) {\n arr[i] = this.getBits(i) ^ other.getBits(i);\n }\n return new goog.math.Integer(arr, this.sign_ ^ other.sign_);\n};\n\n\n/**\n * Returns this value with bits shifted to the left by the given amount.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} This shifted to the left by the given amount.\n */\ngoog.math.Integer.prototype.shiftLeft = function(numBits) {\n 'use strict';\n var arr_delta = numBits >> 5;\n var bit_delta = numBits % 32;\n var len = this.bits_.length + arr_delta + (bit_delta > 0 ? 1 : 0);\n var arr = [];\n for (var i = 0; i < len; i++) {\n if (bit_delta > 0) {\n arr[i] = (this.getBits(i - arr_delta) << bit_delta) |\n (this.getBits(i - arr_delta - 1) >>> (32 - bit_delta));\n } else {\n arr[i] = this.getBits(i - arr_delta);\n }\n }\n return new goog.math.Integer(arr, this.sign_);\n};\n\n\n/**\n * Returns this value with bits shifted to the right by the given amount.\n * @param {number} numBits The number of bits by which to shift.\n * @return {!goog.math.Integer} This shifted to the right by the given amount.\n */\ngoog.math.Integer.prototype.shiftRight = function(numBits) {\n 'use strict';\n var arr_delta = numBits >> 5;\n var bit_delta = numBits % 32;\n var len = this.bits_.length - arr_delta;\n var arr = [];\n for (var i = 0; i < len; i++) {\n if (bit_delta > 0) {\n arr[i] = (this.getBits(i + arr_delta) >>> bit_delta) |\n (this.getBits(i + arr_delta + 1) << (32 - bit_delta));\n } else {\n arr[i] = this.getBits(i + arr_delta);\n }\n }\n return new goog.math.Integer(arr, this.sign_);\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Transport support for WebChannel.\n *\n * The <code>WebChannelTransport</code> implementation serves as the factory\n * for <code>WebChannel</code>, which offers an abstraction for\n * point-to-point socket-like communication similar to what BrowserChannel\n * or HTML5 WebSocket offers.\n */\n\ngoog.provide('goog.net.WebChannelTransport');\n\ngoog.requireType('goog.net.WebChannel');\ngoog.requireType('goog.net.WebChannel.Options');\n\n\n\n/**\n * A WebChannelTransport instance represents a shared context of logical\n * connectivity between a browser client and a remote origin.\n *\n * Over a single WebChannelTransport instance, multiple WebChannels may be\n * created against different URLs, which may all share the same\n * underlying connectivity (i.e. TCP connection) whenever possible.\n *\n * When multi-domains are supported, such as CORS, multiple origins may be\n * supported over a single WebChannelTransport instance at the same time.\n *\n * Sharing between different window contexts such as tabs is not addressed\n * by WebChannelTransport. Applications may choose HTML5 shared workers\n * or other techniques to access the same transport instance\n * across different window contexts.\n *\n * @interface\n */\ngoog.net.WebChannelTransport = function() {};\n\n\n/**\n * The client version. This integer value will be passed to the server\n * when a channel is opened to inform the server the client \"capabilities\".\n *\n * Wire protocol version is a different concept and is internal to the\n * transport implementation.\n *\n * @const\n * @type {number}\n */\ngoog.net.WebChannelTransport.CLIENT_VERSION = 22;\n\n\n/**\n * Create a new WebChannel instance.\n *\n * The new WebChannel is to be opened against the server-side resource\n * as specified by the given URL. See {@link goog.net.WebChannel} for detailed\n * semantics.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance. The configuration object is reusable after\n * the new channel instance is created.\n * @return {!goog.net.WebChannel} the newly created WebChannel instance.\n */\ngoog.net.WebChannelTransport.prototype.createWebChannel = goog.abstractMethod;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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.net.FetchXmlHttpFactory');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\n\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\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;\ngoog.net.XhrIo.prototype['setWithCredentials'] =\n goog.net.XhrIo.prototype.setWithCredentials;\n\ngoog.require('goog.crypt.Md5');\ngoog.crypt.Md5.prototype['digest'] = goog.crypt.Md5.prototype.digest;\ngoog.crypt.Md5.prototype['reset'] = goog.crypt.Md5.prototype.reset;\ngoog.crypt.Md5.prototype['update'] = goog.crypt.Md5.prototype.update;\n\ngoog.require('goog.math.Integer');\ngoog.math.Integer.prototype['add'] = goog.math.Integer.prototype.add;\ngoog.math.Integer.prototype['multiply'] = goog.math.Integer.prototype.multiply;\ngoog.math.Integer.prototype['modulo'] = goog.math.Integer.prototype.modulo;\ngoog.math.Integer.prototype['compare'] = goog.math.Integer.prototype.compare;\ngoog.math.Integer.prototype['toNumber'] = goog.math.Integer.prototype.toNumber;\ngoog.math.Integer.prototype['toString'] = goog.math.Integer.prototype.toString;\ngoog.math.Integer.prototype['getBits'] = goog.math.Integer.prototype.getBits;\ngoog.math.Integer['fromNumber'] = goog.math.Integer.fromNumber;\ngoog.math.Integer['fromString'] = goog.math.Integer.fromString;\n\nmodule['exports']['createWebChannelTransport'] =\n goog.net.createWebChannelTransport;\nmodule['exports']['getStatEventTarget'] =\n goog.labs.net.webChannel.requestStats.getStatEventTarget;\nmodule['exports']['ErrorCode'] = goog.net.ErrorCode;\nmodule['exports']['EventType'] = goog.net.EventType;\nmodule['exports']['Event'] = goog.labs.net.webChannel.requestStats.Event;\nmodule['exports']['Stat'] = goog.labs.net.webChannel.requestStats.Stat;\nmodule['exports']['FetchXmlHttpFactory'] = goog.net.FetchXmlHttpFactory;\nmodule['exports']['WebChannel'] = goog.net.WebChannel;\nmodule['exports']['XhrIo'] = goog.net.XhrIo;\nmodule['exports']['Md5'] = goog.crypt.Md5;\nmodule['exports']['Integer'] = goog.math.Integer;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport { logError } from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n logError('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 if (status === undefined) {\n logError('RPC_ERROR', 'HTTP error has no status');\n return Code.UNKNOWN;\n }\n\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.FAILED_PRECONDITION;\n // Other possibilities based on the forward mapping\n // return Code.INVALID_ARGUMENT;\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(/_/g, '-');\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n * <ul>\n * <li>`debug` for the most verbose logging level, primarily for\n * debugging.</li>\n * <li>`error` to log errors only.</li>\n * <li><code>`silent` to turn off logging.</li>\n * </ul>\n */\nexport function setLogLevel(logLevel: LogLevelString): void {\n logClient.setLogLevel(logLevel);\n}\n\nexport function logDebug(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function logError(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * @internal\n */\nexport function logWarn(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n const args = obj.map(argToString);\n logClient.warn(`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 try {\n return 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n return JSON.stringify(value);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../core/version';\n\nimport { logError } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure: string = 'Unexpected state'): 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 logError(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 *\n * Messages are stripped in production builds.\n */\nexport function hardAssert(\n assertion: boolean,\n message?: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */\nexport function debugAssert(\n assertion: boolean,\n message: string\n): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */\nexport function debugCast<T>(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n debugAssert(\n obj instanceof constructor,\n `Expected type '${constructor.name}', but was '${obj.constructor.name}'`\n );\n return obj as T;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * The set of Firestore status codes. The codes are the same at the ones\n * exposed by gRPC here:\n * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n *\n * Possible values:\n * - 'cancelled': The operation was cancelled (typically by the caller).\n * - 'unknown': Unknown error or an error from a different error domain.\n * - 'invalid-argument': Client specified an invalid argument. Note that this\n * differs from 'failed-precondition'. 'invalid-argument' indicates\n * arguments that are problematic regardless of the state of the system\n * (e.g. an invalid field name).\n * - 'deadline-exceeded': Deadline expired before operation could complete.\n * For operations that change the state of the system, this error may be\n * returned even if the operation has completed successfully. For example,\n * a successful response from a server could have been delayed long enough\n * for the deadline to expire.\n * - 'not-found': Some requested document was not found.\n * - 'already-exists': Some document that we attempted to create already\n * exists.\n * - 'permission-denied': The caller does not have permission to execute the\n * specified operation.\n * - 'resource-exhausted': Some resource has been exhausted, perhaps a\n * per-user quota, or perhaps the entire file system is out of space.\n * - 'failed-precondition': Operation was rejected because the system is not\n * in a state required for the operation's execution.\n * - 'aborted': The operation was aborted, typically due to a concurrency\n * issue like transaction aborts, etc.\n * - 'out-of-range': Operation was attempted past the valid range.\n * - 'unimplemented': Operation is not implemented or not supported/enabled.\n * - 'internal': Internal errors. Means some invariants expected by\n * underlying system has been broken. If you see one of these errors,\n * something is very broken.\n * - 'unavailable': The service is currently unavailable. This is most likely\n * a transient condition and may be corrected by retrying with a backoff.\n * - 'data-loss': Unrecoverable data loss or corruption.\n * - 'unauthenticated': The request does not have valid authentication\n * credentials for the operation.\n */\nexport type FirestoreErrorCode =\n | 'cancelled'\n | 'unknown'\n | 'invalid-argument'\n | 'deadline-exceeded'\n | 'not-found'\n | 'already-exists'\n | 'permission-denied'\n | 'resource-exhausted'\n | 'failed-precondition'\n | 'aborted'\n | 'out-of-range'\n | 'unimplemented'\n | 'internal'\n | 'unavailable'\n | 'data-loss'\n | 'unauthenticated';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = 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 FirestoreErrorCode,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as FirestoreErrorCode,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as FirestoreErrorCode,\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 FirestoreErrorCode,\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 FirestoreErrorCode,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as FirestoreErrorCode,\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 FirestoreErrorCode,\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 FirestoreErrorCode,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as FirestoreErrorCode,\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 FirestoreErrorCode,\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 FirestoreErrorCode,\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 FirestoreErrorCode,\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 FirestoreErrorCode,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as FirestoreErrorCode,\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 FirestoreErrorCode,\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 FirestoreErrorCode,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as FirestoreErrorCode\n};\n\n/** An error returned by a Firestore operation. */\nexport class FirestoreError extends FirebaseError {\n /** The stack of the error. */\n readonly stack?: string;\n\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n readonly code: FirestoreErrorCode,\n /**\n * A custom error description.\n */\n readonly message: string\n ) {\n super(code, 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Resolver<R> {\n (value: R | Promise<R>): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred<R = void> {\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { User } from '../auth/user';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { Deferred } from '../util/promise';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\n/**\n * @internal\n */\nexport type AuthTokenFactory = () => string;\n\n/**\n * @internal\n */\nexport interface FirstPartyCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'firstParty';\n ['sessionIndex']: string;\n ['iamToken']: string | null;\n ['authTokenFactory']: AuthTokenFactory | null;\n}\n\nexport interface ProviderCredentialsSettings {\n // These are external types. Prevent minification.\n ['type']: 'provider';\n ['client']: CredentialsProvider<User>;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';\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 * This will be null for Tokens of the type 'AppCheck'.\n */\n user?: User;\n\n /** Header values to set for this token */\n headers: Map<string, string>;\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n headers = new Map();\n\n constructor(value: string, public user: User) {\n this.headers.set('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<T> = (credential: T) => Promise<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<T> {\n /**\n * Starts the credentials provider and specifies a listener to be notified of\n * credential changes (sign-in / sign-out, token changes). It is immediately\n * called once with the initial user.\n *\n * The change listener is invoked on the provided AsyncQueue.\n */\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<T>\n ): void;\n\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 shutdown(): void;\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */\nexport class EmptyAuthCredentialsProvider implements CredentialsProvider<User> {\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));\n }\n\n shutdown(): void {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */\nexport class EmulatorAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n constructor(private token: Token) {}\n\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<User> | null = null;\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n debugAssert(\n !this.changeListener,\n 'Can only call setChangeListener() once.'\n );\n this.changeListener = changeListener;\n // Fire with initial user.\n asyncQueue.enqueueRetryable(() => changeListener(this.token.user!));\n }\n\n shutdown(): void {\n this.changeListener = null;\n }\n}\n\n/** Credential provider for the Lite SDK. */\nexport class LiteAuthCredentialsProvider implements CredentialsProvider<User> {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider<FirebaseAuthInternalName>) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise<Token | null> {\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken().then(tokenData => {\n if (tokenData) {\n hardAssert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(\n tokenData.accessToken,\n new User(this.auth!.getUid())\n );\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener!: () => void;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\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 private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(private authProvider: Provider<FirebaseAuthInternalName>) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n let lastTokenId = this.tokenCounter;\n\n // A change listener that prevents double-firing for the same token change.\n const guardedChangeListener: (user: User) => Promise<void> = user => {\n if (this.tokenCounter !== lastTokenId) {\n lastTokenId = this.tokenCounter;\n return changeListener(user);\n } else {\n return Promise.resolve();\n }\n };\n\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let nextToken = new Deferred<void>();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred<void>();\n asyncQueue.enqueueRetryable(() =>\n guardedChangeListener(this.currentUser)\n );\n };\n\n const awaitNextToken: () => void = () => {\n const currentTokenAttempt = nextToken;\n asyncQueue.enqueueRetryable(async () => {\n await currentTokenAttempt.promise;\n await guardedChangeListener(this.currentUser);\n });\n };\n\n const registerAuth = (auth: FirebaseAuthInternal): void => {\n logDebug('FirebaseAuthCredentialsProvider', 'Auth detected');\n this.auth = auth;\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n };\n\n this.authProvider.onInit(auth => registerAuth(auth));\n\n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout(() => {\n if (!this.auth) {\n const auth = this.authProvider.getImmediate({ optional: true });\n if (auth) {\n registerAuth(auth);\n } else {\n // If auth is still not available, proceed with `null` user\n logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected');\n nextToken.resolve();\n nextToken = new Deferred<void>();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise<Token | null> {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAuthCredentialsProvider not started.'\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 logDebug(\n 'FirebaseAuthCredentialsProvider',\n 'getToken aborted due to token change.'\n );\n return this.getToken();\n } else {\n if (tokenData) {\n hardAssert(\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 shutdown(): void {\n if (this.auth) {\n this.auth.removeAuthTokenListener(this.tokenListener!);\n }\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 hardAssert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\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 private _headers = new Map();\n\n constructor(\n private readonly sessionIndex: string,\n private readonly iamToken: string | null,\n private readonly authTokenFactory: AuthTokenFactory | null\n ) {}\n\n /**\n * Gets an authorization token, using a provided factory function, or return\n * null.\n */\n private getAuthToken(): string | null {\n if (this.authTokenFactory) {\n return this.authTokenFactory();\n } else {\n return null;\n }\n }\n\n get headers(): Map<string, string> {\n this._headers.set('X-Goog-AuthUser', this.sessionIndex);\n // Use array notation to prevent minification\n const authHeaderTokenValue = this.getAuthToken();\n if (authHeaderTokenValue) {\n this._headers.set('Authorization', authHeaderTokenValue);\n }\n if (this.iamToken) {\n this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);\n }\n\n return this._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 FirstPartyAuthCredentialsProvider\n implements CredentialsProvider<User>\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(\n new FirstPartyToken(\n this.sessionIndex,\n this.iamToken,\n this.authTokenFactory\n )\n );\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<User>\n ): void {\n // Fire with initial uid.\n asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));\n }\n\n shutdown(): void {}\n\n invalidateToken(): void {}\n}\n\nexport class AppCheckToken implements Token {\n type = 'AppCheck' as TokenType;\n headers = new Map();\n\n constructor(private value: string) {\n if (value && value.length > 0) {\n this.headers.set('x-firebase-appcheck', this.value);\n }\n }\n}\n\nexport class FirebaseAppCheckTokenProvider\n implements CredentialsProvider<string>\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener!: AppCheckTokenListener;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n\n constructor(\n private appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise<void> = tokenResult => {\n if (tokenResult.error != null) {\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`\n );\n }\n const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;\n this.latestAppCheckToken = tokenResult.token;\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n `Received ${tokenUpdated ? 'new' : 'existing'} token.`\n );\n return tokenUpdated\n ? changeListener(tokenResult.token)\n : Promise.resolve();\n };\n\n this.tokenListener = (tokenResult: AppCheckTokenResult) => {\n asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));\n };\n\n const registerAppCheck = (appCheck: FirebaseAppCheckInternal): void => {\n logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected');\n this.appCheck = appCheck;\n this.appCheck.addTokenListener(this.tokenListener);\n };\n\n this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck));\n\n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout(() => {\n if (!this.appCheck) {\n const appCheck = this.appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n registerAppCheck(appCheck);\n } else {\n // If AppCheck is still not available, proceed without it.\n logDebug(\n 'FirebaseAppCheckTokenProvider',\n 'AppCheck not yet detected'\n );\n }\n }\n }, 0);\n }\n\n getToken(): Promise<Token | null> {\n debugAssert(\n this.tokenListener != null,\n 'FirebaseAppCheckTokenProvider not started.'\n );\n\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken(forceRefresh).then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n this.latestAppCheckToken = tokenResult.token;\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n shutdown(): void {\n if (this.appCheck) {\n this.appCheck.removeTokenListener(this.tokenListener!);\n }\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider<string> {\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider<string> {\n private appCheck: FirebaseAppCheckInternal | null = null;\n\n constructor(\n private appCheckProvider: Provider<AppCheckInternalComponentName>\n ) {\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise<Token | null> {\n if (!this.appCheck) {\n return Promise.resolve(null);\n }\n\n return this.appCheck.getToken().then(tokenResult => {\n if (tokenResult) {\n hardAssert(\n typeof tokenResult.token === 'string',\n 'Invalid tokenResult returned from getToken():' + tokenResult\n );\n return new AppCheckToken(tokenResult.token);\n } else {\n return null;\n }\n });\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener<string>\n ): void {}\n\n shutdown(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeAuthCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider<User> {\n if (!credentials) {\n return new EmptyAuthCredentialsProvider();\n }\n switch (credentials['type']) {\n case 'firstParty':\n return new FirstPartyAuthCredentialsProvider(\n credentials['sessionIndex'] || '0',\n credentials['iamToken'] || null,\n credentials['authTokenFactory'] || null\n );\n\n case 'provider':\n return credentials['client'];\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeAuthCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler<E> = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\n/**\n * A utility class for generating unique alphanumeric IDs of a specified length.\n *\n * @internal\n * Exported internally for testing purposes.\n */\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n // The largest byte value that is a multiple of `char.length`.\n const maxMultiple = Math.floor(256 / chars.length) * chars.length;\n debugAssert(\n 0 < maxMultiple && maxMultiple < 256,\n `Expect maxMultiple to be (0, 256), but got ${maxMultiple}`\n );\n\n let autoId = '';\n const targetLength = 20;\n while (autoId.length < targetLength) {\n const bytes = randomBytes(40);\n for (let i = 0; i < bytes.length; ++i) {\n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n if (autoId.length < targetLength && bytes[i] < maxMultiple) {\n autoId += chars.charAt(bytes[i] % chars.length);\n }\n }\n }\n debugAssert(autoId.length === targetLength, 'Invalid auto ID: ' + autoId);\n\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\nexport interface Equatable<T> {\n isEqual(other: T): boolean;\n}\n\nexport interface Iterable<V> {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals<T>(\n left: T[],\n right: T[],\n comparator: (l: T, r: T) => boolean\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => comparator(value, right[index]));\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../../util/assert';\n\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nexport function randomBytes(nBytes: number): Uint8Array {\n debugAssert(nBytes >= 0, `Expecting non-negative nBytes, got: ${nBytes}`);\n\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const crypto =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof self !== 'undefined' && (self.crypto || (self as any)['msCrypto']);\n const bytes = new Uint8Array(nBytes);\n if (crypto && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n // Falls back to Math.random\n for (let i = 0; i < nBytes; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return bytes;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\n// Number of nanoseconds in a millisecond.\nconst MS_TO_NANOS = 1e6;\n\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nexport class Timestamp {\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n readonly seconds: number,\n /**\n * The fractions of a second at nanosecond resolution.*\n */\n readonly nanoseconds: number\n ) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;\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 /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n /** Returns a textual representation of this `Timestamp`. */\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n /** Returns a JSON-serializable representation of this `Timestamp`. */\n toJSON(): { seconds: number; nanoseconds: number } {\n return { seconds: this.seconds, nanoseconds: this.nanoseconds };\n }\n\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */\n valueOf(): string {\n // This method returns a string of the form <seconds>.<nanoseconds> where\n // <seconds> is translated to have a non-negative value and both <seconds>\n // and <nanoseconds> are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The <seconds> translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-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 fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static min(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(0, 0));\n }\n\n static max(): SnapshotVersion {\n return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, 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 debugAssert(\n this.length >= size,\n \"Can't call popFirst() with less segments\"\n );\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n debugAssert(!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 debugAssert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n debugAssert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n debugAssert(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 *\n * @internal\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 * Returns a string representation of this path\n * where each path segment has been encoded with\n * `encodeURIComponent`.\n */\n toUriEncodedString(): string {\n return this.toArray().map(encodeURIComponent).join('/');\n }\n\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */\n static fromString(...pathComponents: 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 const segments: string[] = [];\n for (const path of pathComponents) {\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid segment (${path}). Paths must not contain // in them.`\n );\n }\n // Strip leading and traling slashed.\n segments.push(...path.split('/').filter(segment => segment.length > 0));\n }\n\n return new ResourcePath(segments);\n }\n\n static emptyPath(): ResourcePath {\n return new ResourcePath([]);\n }\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */\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(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`');\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 emptyPath(): FieldPath {\n return new FieldPath([]);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\n\nimport { ResourcePath } from './path';\n\n/**\n * @internal\n */\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n debugAssert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n static fromPath(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n\n static fromName(name: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(name).popFirst(5));\n }\n\n static empty(): DocumentKey {\n return new DocumentKey(ResourcePath.emptyPath());\n }\n\n get collectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.popLast().lastSegment();\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 /** Returns the collection group (i.e. the name of the parent collection) for this key. */\n getCollectionGroup(): string {\n debugAssert(\n !this.path.isEmpty(),\n 'Cannot get collection group for empty key'\n );\n return this.path.get(this.path.length - 2);\n }\n\n /** Returns the fully qualified path to the parent collection. */\n getCollectionPath(): ResourcePath {\n return this.path.popLast();\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 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 segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { primitiveComparator } from '../util/misc';\n\nimport { Document } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldPath } from './path';\n\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_LARGEST_BATCH_ID = -1;\n\n/**\n * The initial sequence number for each index. Gets updated during index\n * backfill.\n */\nexport const INITIAL_SEQUENCE_NUMBER = 0;\n\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nexport class FieldIndex {\n /** An ID for an index that has not yet been added to persistence. */\n static UNKNOWN_ID = -1;\n\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n readonly indexId: number,\n /** The collection ID this index applies to. */\n readonly collectionGroup: string,\n /** The field segments for this index. */\n readonly fields: IndexSegment[],\n /** Shows how up-to-date the index is for the current user. */\n readonly indexState: IndexState\n ) {}\n}\n\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nexport function fieldIndexGetArraySegment(\n fieldIndex: FieldIndex\n): IndexSegment | undefined {\n return fieldIndex.fields.find(s => s.kind === IndexKind.CONTAINS);\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */\nexport function fieldIndexGetDirectionalSegments(\n fieldIndex: FieldIndex\n): IndexSegment[] {\n return fieldIndex.fields.filter(s => s.kind !== IndexKind.CONTAINS);\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\nexport function fieldIndexGetKeyOrder(fieldIndex: FieldIndex): IndexKind {\n const directionalSegments = fieldIndexGetDirectionalSegments(fieldIndex);\n return directionalSegments.length === 0\n ? IndexKind.ASCENDING\n : directionalSegments[directionalSegments.length - 1].kind;\n}\n\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nexport function fieldIndexSemanticComparator(\n left: FieldIndex,\n right: FieldIndex\n): number {\n let cmp = primitiveComparator(left.collectionGroup, right.collectionGroup);\n if (cmp !== 0) {\n return cmp;\n }\n\n for (let i = 0; i < Math.min(left.fields.length, right.fields.length); ++i) {\n cmp = indexSegmentComparator(left.fields[i], right.fields[i]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return primitiveComparator(left.fields.length, right.fields.length);\n}\n\n/** Returns a debug representation of the field index */\nexport function fieldIndexToString(fieldIndex: FieldIndex): string {\n return `id=${fieldIndex.indexId}|cg=${\n fieldIndex.collectionGroup\n }|f=${fieldIndex.fields.map(f => `${f.fieldPath}:${f.kind}`).join(',')}`;\n}\n\n/** The type of the index, e.g. for which type of query it can be used. */\nexport const enum IndexKind {\n // Note: The order of these values cannot be changed as the enum values are\n // stored in IndexedDb.\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n ASCENDING,\n /**\n * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.\n */\n DESCENDING,\n /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */\n CONTAINS\n}\n\n/** An index component consisting of field path and index type. */\nexport class IndexSegment {\n constructor(\n /** The field path of the component. */\n readonly fieldPath: FieldPath,\n /** The fields sorting order. */\n readonly kind: IndexKind\n ) {}\n}\n\nfunction indexSegmentComparator(\n left: IndexSegment,\n right: IndexSegment\n): number {\n const cmp = FieldPath.comparator(left.fieldPath, right.fieldPath);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.kind, right.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */\nexport class IndexState {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n readonly sequenceNumber: number,\n /** The the latest indexed read time, document and batch id. */\n readonly offset: IndexOffset\n ) {}\n\n /** The state of an index that has not yet been backfilled. */\n static empty(): IndexState {\n return new IndexState(INITIAL_SEQUENCE_NUMBER, IndexOffset.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */\nexport function newIndexOffsetSuccessorFromReadTime(\n readTime: SnapshotVersion,\n largestBatchId: number\n): IndexOffset {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const successorSeconds = readTime.toTimestamp().seconds;\n const successorNanos = readTime.toTimestamp().nanoseconds + 1;\n const successor = SnapshotVersion.fromTimestamp(\n successorNanos === 1e9\n ? new Timestamp(successorSeconds + 1, 0)\n : new Timestamp(successorSeconds, successorNanos)\n );\n return new IndexOffset(successor, DocumentKey.empty(), largestBatchId);\n}\n\n/** Creates a new offset based on the provided document. */\nexport function newIndexOffsetFromDocument(document: Document): IndexOffset {\n return new IndexOffset(\n document.readTime,\n document.key,\n INITIAL_LARGEST_BATCH_ID\n );\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */\nexport class IndexOffset {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n readonly readTime: SnapshotVersion,\n\n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n readonly documentKey: DocumentKey,\n\n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n readonly largestBatchId: number\n ) {}\n\n /** Returns an offset that sorts before all regular offsets. */\n static min(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.min(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n\n /** Returns an offset that sorts after all regular offsets. */\n static max(): IndexOffset {\n return new IndexOffset(\n SnapshotVersion.max(),\n DocumentKey.empty(),\n INITIAL_LARGEST_BATCH_ID\n );\n }\n}\n\nexport function indexOffsetComparator(\n left: IndexOffset,\n right: IndexOffset\n): number {\n let cmp = left.readTime.compareTo(right.readTime);\n if (cmp !== 0) {\n return cmp;\n }\n cmp = DocumentKey.comparator(left.documentKey, right.documentKey);\n if (cmp !== 0) {\n return cmp;\n }\n return primitiveComparator(left.largestBatchId, right.largestBatchId);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from '../core/types';\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/** The different modes supported by `Persistence.runTransaction()`. */\nexport type PersistenceTransactionMode =\n | 'readonly'\n | 'readwrite'\n | 'readwrite-primary';\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 * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { IndexManager } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { PRIMARY_LEASE_LOST_ERROR_MSG } from './persistence_transaction';\n\nexport interface LocalStore {\n collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults>;\n\n /** Manages the list of active field and collection indices. */\n indexManager: IndexManager;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments: LocalDocumentsView;\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 * @returns 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 logDebug('LocalStore', 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 as Error);\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> =\n PersistencePromise.resolve<boolean>(false);\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 * Concurrently map all array elements through asynchronous function.\n */\n static mapArray<T, U>(\n array: T[],\n f: (t: T) => PersistencePromise<U>\n ): PersistencePromise<U[]> {\n return new PersistencePromise<U[]>((resolve, reject) => {\n const expectedCount = array.length;\n const results: U[] = new Array(expectedCount);\n let resolvedCount = 0;\n for (let i = 0; i < expectedCount; i++) {\n const current = i;\n f(array[current]).next(\n result => {\n results[current] = result;\n ++resolvedCount;\n if (resolvedCount === expectedCount) {\n resolve(results);\n }\n },\n err => reject(err)\n );\n }\n });\n }\n\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */\n static doWhile(\n condition: () => boolean,\n action: () => PersistencePromise<void>\n ): PersistencePromise<void> {\n return new PersistencePromise<void>((resolve, reject) => {\n const process = (): void => {\n if (condition() === true) {\n action().next(() => {\n process();\n }, reject);\n } else {\n resolve();\n }\n };\n process();\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA, isIndexedDBAvailable } from '@firebase/util';\n\nimport { debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { PersistencePromise } from './persistence_promise';\n\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise<void>;\n}\n\n/**\n * 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 action: string,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n try {\n return new SimpleDbTransaction(\n action,\n db.transaction(objectStoreNames, mode)\n );\n } catch (e) {\n throw new IndexedDbTransactionError(action, e as Error);\n }\n }\n\n constructor(\n private readonly action: string,\n private readonly transaction: IDBTransaction\n ) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(\n new IndexedDbTransactionError(action, transaction.error)\n );\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(\n new IndexedDbTransactionError(action, error)\n );\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 logDebug(\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 maybeCommit(): void {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeV3IndexedDb = this.transaction as any;\n if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {\n maybeV3IndexedDb.commit();\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 debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore<KeyType, ValueType>(store);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n private db?: IDBDatabase;\n private versionchangelistener?: (event: IDBVersionChangeEvent) => void;\n\n /** Deletes the specified database. */\n static delete(name: string): Promise<void> {\n logDebug(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 (!isIndexedDBAvailable()) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\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].split('_').slice(0, 2).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].split('.').slice(0, 2).join('.')\n : '-1';\n return Number(version);\n }\n\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(\n private readonly name: string,\n private readonly version: number,\n private readonly schemaConverter: SimpleDbSchemaConverter\n ) {\n debugAssert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n\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 logError(\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 /**\n * Opens the specified database, creating or upgrading it if necessary.\n */\n async ensureDb(action: string): Promise<IDBDatabase> {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise<IDBDatabase>((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 = indexedDB.open(this.name, this.version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(db);\n };\n\n request.onblocked = () => {\n reject(\n new IndexedDbTransactionError(\n action,\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 if (error.name === 'InvalidStateError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Unable to open an IndexedDB connection. This could be due to running in a ' +\n 'private browsing session on a browser whose private browsing sessions do not ' +\n 'support IndexedDB: ' +\n error\n )\n );\n } else {\n reject(new IndexedDbTransactionError(action, error));\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n logDebug(\n LOG_TAG,\n 'Database \"' + this.name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n this.schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n this.version\n )\n .next(() => {\n logDebug(\n LOG_TAG,\n 'Database upgrade to version ' + this.version + ' complete'\n );\n });\n };\n });\n }\n\n if (this.versionchangelistener) {\n this.db.onversionchange = event => this.versionchangelistener!(event);\n }\n return this.db;\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.versionchangelistener = versionChangeListener;\n if (this.db) {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n }\n\n async runTransaction<T>(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise<T>\n ): Promise<T> {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n try {\n this.db = await this.ensureDb(action);\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n action,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n const transactionFnResult = transactionFn(transaction)\n .next(result => {\n transaction.maybeCommit();\n return result;\n })\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 (e) {\n const error = e as Error;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n logDebug(\n LOG_TAG,\n 'Transaction failed with error:',\n error.message,\n 'Retrying:',\n retryable\n );\n\n this.close();\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n if (this.db) {\n this.db.close();\n }\n this.db = undefined;\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/** An error that wraps exceptions that thrown during IndexedDB execution. */\nexport class IndexedDbTransactionError extends FirestoreError {\n name = 'IndexedDbTransactionError';\n\n constructor(actionName: string, cause: Error | string) {\n super(\n Code.UNAVAILABLE,\n `IndexedDB transaction '${actionName}' failed: ${cause}`\n );\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */\nexport function isIndexedDbTransactionError(e: Error): boolean {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return e.name === 'IndexedDbTransactionError';\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 logDebug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n logDebug(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 * @returns The key of the value to add.\n */\n add(value: ValueType): PersistencePromise<KeyType> {\n logDebug(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 * @returns 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 logDebug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise<void> {\n logDebug(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 logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest<number>(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise<ValueType[]>;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise<ValueType[]>;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise<ValueType[]>;\n /**\n * Loads all elements from the object store that fall into the provided in the\n * index range for the given index.\n */\n loadAll(index: string, range: IDBKeyRange): PersistencePromise<ValueType[]>;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<ValueType[]> {\n const iterateOptions = this.options(indexOrRange, range);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster.\n const store = iterateOptions.index\n ? this.store.index(iterateOptions.index)\n : this.store;\n if (typeof store.getAll === 'function') {\n const request = store.getAll(iterateOptions.range);\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\n });\n } else {\n const cursor = this.cursor(iterateOptions);\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n }\n\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */\n loadFirst(\n range: IDBKeyRange,\n count: number | null\n ): PersistencePromise<ValueType[]> {\n const request = this.store.getAll(\n range,\n count === null ? undefined : count\n );\n return new PersistencePromise((resolve, reject) => {\n request.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n request.onsuccess = (event: Event) => {\n resolve((event.target as IDBRequest).result);\n };\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 logDebug(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\n * 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(() => PersistencePromise.waitFor(results));\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 debugAssert(\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 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n private task: DelayedOperation<void> | null;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly backfiller: IndexBackfiller\n ) {\n this.task = null;\n }\n\n start(): void {\n debugAssert(\n this.task === null,\n 'Cannot start an already started IndexBackfillerScheduler'\n );\n this.schedule(INITIAL_BACKFILL_DELAY_MS);\n }\n\n stop(): void {\n if (this.task) {\n this.task.cancel();\n this.task = null;\n }\n }\n\n get started(): boolean {\n return this.task !== null;\n }\n\n private schedule(delay: number): void {\n debugAssert(\n this.task === null,\n 'Cannot schedule IndexBackfiller while a task is pending'\n );\n logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n this.task = this.asyncQueue.enqueueAfterDelay(\n TimerId.IndexBackfill,\n delay,\n async () => {\n this.task = null;\n try {\n const documentsProcessed = await this.backfiller.backfill();\n logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during index backfill: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n }\n );\n }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n private readonly localStore: LocalStore,\n private readonly persistence: Persistence\n ) {}\n\n async backfill(\n maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n ): Promise<number> {\n return this.persistence.runTransaction(\n 'Backfill Indexes',\n 'readwrite-primary',\n txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n );\n }\n\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n private writeIndexEntries(\n transation: PersistenceTransaction,\n maxDocumentsToProcess: number\n ): PersistencePromise<number> {\n const processedCollectionGroups = new Set<string>();\n let documentsRemaining = maxDocumentsToProcess;\n let continueLoop = true;\n return PersistencePromise.doWhile(\n () => continueLoop === true && documentsRemaining > 0,\n () => {\n return this.localStore.indexManager\n .getNextCollectionGroupToUpdate(transation)\n .next((collectionGroup: string | null) => {\n if (\n collectionGroup === null ||\n processedCollectionGroups.has(collectionGroup)\n ) {\n continueLoop = false;\n } else {\n logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`);\n return this.writeEntriesForCollectionGroup(\n transation,\n collectionGroup,\n documentsRemaining\n ).next(documentsProcessed => {\n documentsRemaining -= documentsProcessed;\n processedCollectionGroups.add(collectionGroup);\n });\n }\n });\n }\n ).next(() => maxDocumentsToProcess - documentsRemaining);\n }\n\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */\n private writeEntriesForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n documentsRemainingUnderCap: number\n ): PersistencePromise<number> {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager\n .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n .next(existingOffset =>\n this.localStore.localDocuments\n .getNextDocuments(\n transaction,\n collectionGroup,\n existingOffset,\n documentsRemainingUnderCap\n )\n .next(nextBatch => {\n const docs: DocumentMap = nextBatch.changes;\n return this.localStore.indexManager\n .updateIndexEntries(transaction, docs)\n .next(() => this.getNewOffset(existingOffset, nextBatch))\n .next(newOffset => {\n logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n return this.localStore.indexManager.updateCollectionGroup(\n transaction,\n collectionGroup,\n newOffset\n );\n })\n .next(() => docs.size);\n })\n );\n }\n\n /** Returns the next offset based on the provided documents. */\n private getNewOffset(\n existingOffset: IndexOffset,\n lookupResult: LocalWriteResult\n ): IndexOffset {\n let maxOffset: IndexOffset = existingOffset;\n lookupResult.changes.forEach((key, document) => {\n const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n maxOffset = newOffset;\n }\n });\n return new IndexOffset(\n maxOffset.readTime,\n maxOffset.documentKey,\n Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ResourcePath } from '../model/path';\nimport { fail, hardAssert } 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 encodeResourcePath(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 decodeResourcePath(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 hardAssert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n hardAssert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 'Non-empty path ' + path + ' had length 2'\n );\n return ResourcePath.emptyPath();\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 * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, TargetId } from '../core/types';\nimport { ResourcePath } from '../model/path';\nimport { fail } from '../util/assert';\n\nimport {\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { DbDocumentMutation } from './indexeddb_schema';\nimport { DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy } from './indexeddb_schema_legacy';\n\n// This file contains static constants and helper functions for IndexedDB.\n// It is split from indexeddb_schema to allow for minification.\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 DbPrimaryClientKey;\n\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\nexport const DbPrimaryClientStore = 'owner';\n\n/**\n * The key string used for the single object that exists in the\n * DbPrimaryClient store.\n */\n\nexport const DbPrimaryClientKey = 'owner';\n\n/** Object keys in the 'mutationQueues' store are userId strings. */\nexport type DbMutationQueueKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationQueueStore = 'mutationQueues';\n\n/** Keys are automatically assigned via the userId property. */\nexport const DbMutationQueueKeyPath = 'userId';\n\n/** The 'mutations' store is keyed by batch ID. */\nexport type DbMutationBatchKey = BatchId;\n\n/** Name of the IndexedDb object store. */\nexport const DbMutationBatchStore = 'mutations';\n\n/** Keys are automatically assigned via the userId, batchId properties. */\nexport const DbMutationBatchKeyPath = 'batchId';\n\n/** The index name for lookup of mutations by user. */\n\nexport const DbMutationBatchUserMutationsIndex = 'userMutationsIndex';\n\n/** The user mutations index is keyed by [userId, batchId] pairs. */\nexport const DbMutationBatchUserMutationsKeyPath = ['userId', 'batchId'];\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\n/**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\nexport function newDbDocumentMutationPrefixForUser(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 */\nexport function newDbDocumentMutationPrefixForPath(\n userId: string,\n path: ResourcePath\n): [string, EncodedResourcePath] {\n return [userId, encodeResourcePath(path)];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\nexport function newDbDocumentMutationKey(\n userId: string,\n path: ResourcePath,\n batchId: BatchId\n): DbDocumentMutationKey {\n return [userId, encodeResourcePath(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 */\nexport const DbDocumentMutationPlaceholder: DbDocumentMutation = {};\n\nexport const DbDocumentMutationStore = 'documentMutations';\n\nexport const DbRemoteDocumentStore = 'remoteDocumentsV14';\n\n/**\n * A key in the 'remoteDocumentsV14' object store is an array containing the\n * collection path, the collection group, the read time and the document id.\n */\nexport type DbRemoteDocumentKey = [\n /** path to collection */ string[],\n /** collection group */ string,\n /** read time */ DbTimestampKey,\n /** document ID */ string\n];\n\n/**\n * The primary key of the remote documents store, which allows for efficient\n * access by collection path and read time.\n */\nexport const DbRemoteDocumentKeyPath = [\n 'prefixPath',\n 'collectionGroup',\n 'readTime',\n 'documentId'\n];\n\n/** An index that provides access to documents by key. */\nexport const DbRemoteDocumentDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbRemoteDocumentDocumentKeyIndexPath = [\n 'prefixPath',\n 'collectionGroup',\n 'documentId'\n];\n\n/**\n * An index that provides access to documents by collection group and read\n * time.\n *\n * This index is used by the index backfiller.\n */\nexport const DbRemoteDocumentCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbRemoteDocumentCollectionGroupIndexPath = [\n 'collectionGroup',\n 'readTime',\n 'prefixPath',\n 'documentId'\n];\n\nexport const DbRemoteDocumentGlobalStore = 'remoteDocumentGlobal';\n\nexport const DbRemoteDocumentGlobalKey = 'remoteDocumentGlobalKey';\n\nexport type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobalKey;\n\n/**\n * A key in the 'targets' object store is a targetId of the query.\n */\nexport type DbTargetKey = TargetId;\n\nexport const DbTargetStore = 'targets';\n\n/** Keys are automatically assigned via the targetId property. */\nexport const DbTargetKeyPath = 'targetId';\n\n/** The name of the queryTargets index. */\nexport const DbTargetQueryTargetsIndexName = '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 */\nexport const DbTargetQueryTargetsKeyPath = ['canonicalId', 'targetId'];\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/** Name of the IndexedDb object store. */\nexport const DbTargetDocumentStore = 'targetDocuments';\n\n/** Keys are automatically assigned via the targetId, path properties. */\nexport const DbTargetDocumentKeyPath = ['targetId', 'path'];\n\n/** The index name for the reverse index. */\nexport const DbTargetDocumentDocumentTargetsIndex = 'documentTargetsIndex';\n\n/** We also need to create the reverse index for these properties. */\nexport const DbTargetDocumentDocumentTargetsKeyPath = ['path', 'targetId'];\n\n/**\n * The type to represent the single allowed key for the DbTargetGlobal store.\n */\nexport type DbTargetGlobalKey = typeof DbTargetGlobalKey;\n/**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\nexport const DbTargetGlobalKey = 'targetGlobalKey';\n\nexport const DbTargetGlobalStore = 'targetGlobal';\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/** Name of the IndexedDb object store. */\nexport const DbCollectionParentStore = 'collectionParents';\n\n/** Keys are automatically assigned via the collectionId, parent properties. */\nexport const DbCollectionParentKeyPath = ['collectionId', 'parent'];\n\n/** Name of the IndexedDb object store. */\nexport const DbClientMetadataStore = 'clientMetadata';\n\n/** Keys are automatically assigned via the clientId properties. */\nexport const DbClientMetadataKeyPath = 'clientId';\n\n/** Object keys in the 'clientMetadata' store are clientId strings. */\nexport type DbClientMetadataKey = string;\n\nexport type DbBundlesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbBundleStore = 'bundles';\n\nexport const DbBundleKeyPath = 'bundleId';\n\nexport type DbNamedQueriesKey = string;\n\n/** Name of the IndexedDb object store. */\nexport const DbNamedQueryStore = 'namedQueries';\n\nexport const DbNamedQueryKeyPath = 'name';\n\n/** The key for each index consisting of just the index id. */\nexport type DbIndexConfigurationKey = number;\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexConfigurationStore = 'indexConfiguration';\n\nexport const DbIndexConfigurationKeyPath = 'indexId';\n\n/**\n * An index that provides access to the index configurations by collection\n * group.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexConfigurationCollectionGroupIndex = 'collectionGroupIndex';\n\nexport const DbIndexConfigurationCollectionGroupIndexPath = 'collectionGroup';\n\n/** The key for each index state consisting of the index id and its user id. */\nexport type DbIndexStateKey = [number, string];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexStateStore = 'indexState';\n\nexport const DbIndexStateKeyPath = ['indexId', 'uid'];\n\n/**\n * An index that provides access to documents in a collection sorted by last\n * update time. Used by the backfiller.\n *\n * PORTING NOTE: iOS and Android maintain this index in-memory, but this is\n * not possible here as the Web client supports concurrent access to\n * persistence via multi-tab.\n */\nexport const DbIndexStateSequenceNumberIndex = 'sequenceNumberIndex';\n\nexport const DbIndexStateSequenceNumberIndexPath = ['uid', 'sequenceNumber'];\n\n/**\n * The key for each index entry consists of the index id and its user id,\n * the encoded array and directional value for the indexed fields as well as\n * an ordered and an encoded document path for the indexed document.\n */\nexport type DbIndexEntryKey = [\n number,\n string,\n Uint8Array,\n Uint8Array,\n Uint8Array,\n string[]\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbIndexEntryStore = 'indexEntries';\n\nexport const DbIndexEntryKeyPath = [\n 'indexId',\n 'uid',\n 'arrayValue',\n 'directionalValue',\n 'orderedDocumentKey',\n 'documentKey'\n];\n\nexport const DbIndexEntryDocumentKeyIndex = 'documentKeyIndex';\n\nexport const DbIndexEntryDocumentKeyIndexPath = [\n 'indexId',\n 'uid',\n 'orderedDocumentKey'\n];\n\nexport type DbDocumentOverlayKey = [\n /* userId */ string,\n /* collectionPath */ string,\n /* documentId */ string\n];\n\n/** Name of the IndexedDb object store. */\nexport const DbDocumentOverlayStore = 'documentOverlays';\n\nexport const DbDocumentOverlayKeyPath = [\n 'userId',\n 'collectionPath',\n 'documentId'\n];\n\nexport const DbDocumentOverlayCollectionPathOverlayIndex =\n 'collectionPathOverlayIndex';\n\nexport const DbDocumentOverlayCollectionPathOverlayIndexPath = [\n 'userId',\n 'collectionPath',\n 'largestBatchId'\n];\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndex =\n 'collectionGroupOverlayIndex';\n\nexport const DbDocumentOverlayCollectionGroupOverlayIndexPath = [\n 'userId',\n 'collectionGroup',\n 'largestBatchId'\n];\n\n// Visible for testing\nexport const V1_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStoreLegacy,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore\n];\n\n// Visible for testing\nexport const V3_STORES = V1_STORES;\n// Note: DbRemoteDocumentChanges is no longer used and dropped with v9.\nexport const V4_STORES = [...V3_STORES, DbClientMetadataStore];\nexport const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobalStore];\nexport const V8_STORES = [...V6_STORES, DbCollectionParentStore];\nexport const V11_STORES = [...V8_STORES, DbBundleStore, DbNamedQueryStore];\nexport const V12_STORES = [...V11_STORES, DbDocumentOverlayStore];\nexport const V13_STORES = [\n DbMutationQueueStore,\n DbMutationBatchStore,\n DbDocumentMutationStore,\n DbRemoteDocumentStore,\n DbTargetStore,\n DbPrimaryClientStore,\n DbTargetGlobalStore,\n DbTargetDocumentStore,\n DbClientMetadataStore,\n DbRemoteDocumentGlobalStore,\n DbCollectionParentStore,\n DbBundleStore,\n DbNamedQueryStore,\n DbDocumentOverlayStore\n];\nexport const V14_STORES = V13_STORES;\nexport const V15_STORES = [\n ...V14_STORES,\n DbIndexConfigurationStore,\n DbIndexStateStore,\n DbIndexEntryStore\n];\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 = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 15) {\n return V15_STORES;\n } else if (schemaVersion === 14) {\n return V14_STORES;\n } else if (schemaVersion === 13) {\n return V13_STORES;\n } else if (schemaVersion === 12) {\n return V12_STORES;\n } else if (schemaVersion === 11) {\n return V11_STORES;\n } else {\n fail('Only schema version 11 and 12 and 13 are supported');\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document as ProtoDocument } from '../protos/firestore_proto_api';\n\nimport { DbNoDocument, DbUnknownDocument } from './indexeddb_schema';\nimport { DbTimestampKey } from './indexeddb_sentinels';\n\n// This file contains older schema definitions for object stores that were\n// migrated to newer schema versions. These object stores should only be used\n// during schema migrations.\n\nexport interface DbRemoteDocument {\n unknownDocument?: DbUnknownDocument;\n noDocument?: DbNoDocument;\n document?: ProtoDocument;\n hasCommittedMutations?: boolean;\n readTime?: DbTimestampKey;\n parentPath?: string[];\n}\n\nexport type DbRemoteDocumentKey = string[];\nexport const DbRemoteDocumentStore = 'remoteDocuments';\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugCast } from '../util/assert';\n\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\nexport function getStore<Key extends IDBValidKey, Value>(\n txn: PersistenceTransaction,\n store: string\n): SimpleDbStore<Key, Value> {\n const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n return SimpleDb.getStore<Key, Value>(\n indexedDbTransaction.simpleDbTransaction,\n store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict<V> {\n [stringKey: string]: V;\n}\n\nexport function objectSize(obj: object): 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\nexport function forEach<V>(\n obj: Dict<V> | undefined,\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 mapToArray<V, R>(\n obj: Dict<V>,\n fn: (element: V, key: string, obj: Dict<V>) => R\n): R[] {\n const result: R[] = [];\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result.push(fn(obj[key], key, obj));\n }\n }\n return result;\n}\n\nexport function isEmpty<V>(obj: Dict<V>): boolean {\n debugAssert(\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","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, 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 (startKey && 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 debugAssert(\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 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] &lt;= elem &lt; 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 &lt;= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator<T, boolean>;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet<T> {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet<T> {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet<T>): SortedSet<T> {\n let result: SortedSet<T> = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet<T>): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap<T, boolean>): SortedSet<T> {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator<T> {\n constructor(private iter: SortedMapIterator<T, boolean>) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\nexport function diffSortedSets<T>(\n before: SortedSet<T>,\n after: SortedSet<T>,\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n const beforeIt = before.getIterator();\n const afterIt = after.getIterator();\n\n let beforeValue = advanceIterator(beforeIt);\n let afterValue = advanceIterator(afterIt);\n\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n while (beforeValue || afterValue) {\n let added = false;\n let removed = false;\n\n if (beforeValue && afterValue) {\n const cmp = comparator(beforeValue, afterValue);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n removed = true;\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n added = true;\n }\n } else if (beforeValue != null) {\n removed = true;\n } else {\n added = true;\n }\n\n if (added) {\n onAdd(afterValue!);\n afterValue = advanceIterator(afterIt);\n } else if (removed) {\n onRemove(beforeValue!);\n beforeValue = advanceIterator(beforeIt);\n } else {\n beforeValue = advanceIterator(beforeIt);\n afterValue = advanceIterator(afterIt);\n }\n }\n}\n\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction advanceIterator<T>(it: SortedSetIterator<T>): T | undefined {\n return it.hasNext() ? it.getNext() : undefined;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { FieldPath } from './path';\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: FieldPath[]) {\n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n fields.sort(FieldPath.comparator);\n debugAssert(\n !fields.some((v, i) => i !== 0 && v.isEqual(fields[i - 1])),\n 'FieldMask contains field that is not unique: ' +\n fields.find((v, i) => i !== 0 && v.isEqual(fields[i - 1]))!\n );\n }\n\n static empty(): FieldMask {\n return new FieldMask([]);\n }\n\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */\n unionWith(extraFields: FieldPath[]): FieldMask {\n let mergedMaskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n for (const fieldPath of this.fields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n for (const fieldPath of extraFields) {\n mergedMaskSet = mergedMaskSet.add(fieldPath);\n }\n return new FieldMask(mergedMaskSet.toArray());\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 for (const fieldMaskPath of this.fields) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n return true;\n }\n }\n return false;\n }\n\n isEqual(other: FieldMask): boolean {\n return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));\n }\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { decodeBase64, encodeBase64 } from '../platform/base64';\n\nimport { primitiveComparator } from './misc';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private constructor(private readonly binaryString: string) {}\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = decodeBase64(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n [Symbol.iterator](): Iterator<number> {\n let i = 0;\n return {\n next: () => {\n if (i < this.binaryString.length) {\n return { value: this.binaryString.charCodeAt(i++), done: false };\n } else {\n return { value: undefined, done: true };\n }\n }\n };\n }\n\n toBase64(): string {\n return encodeBase64(this.binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this.binaryString);\n }\n\n approximateByteSize(): number {\n return this.binaryString.length * 2;\n }\n\n compareTo(other: ByteString): number {\n return primitiveComparator(this.binaryString, other.binaryString);\n }\n\n isEqual(other: ByteString): boolean {\n return this.binaryString === other.binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return atob(encoded);\n } catch (e) {\n // Check that `DOMException` is defined before using it to avoid\n // \"ReferenceError: Property 'DOMException' doesn't exist\" in react-native.\n // (https://github.com/firebase/firebase-js-sdk/issues/7115)\n if (typeof DOMException !== 'undefined' && e instanceof DOMException) {\n throw new Base64DecodeError('Invalid base64 string: ' + e);\n } else {\n throw e;\n }\n }\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return btoa(raw);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return typeof atob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../protos/firestore_proto_api';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_TIMESTAMP_REG_EXP = new RegExp(\n /^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/\n);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */\nexport function normalizeTimestamp(date: Timestamp): {\n seconds: number;\n nanos: number;\n} {\n hardAssert(!!date, 'Cannot normalize null or undefined timestamp.');\n\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 // 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_TIMESTAMP_REG_EXP.exec(date);\n hardAssert(!!fraction, 'invalid timestamp: ' + date);\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 parsedDate = new Date(date);\n const seconds = Math.floor(parsedDate.getTime() / 1000);\n\n return { seconds, nanos };\n } else {\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 = normalizeNumber(date.seconds);\n const nanos = normalizeNumber(date.nanos);\n return { seconds, nanos };\n }\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */\nexport function normalizeNumber(value: number | string | undefined): 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 0;\n }\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */\nexport function normalizeByteString(blob: string | Uint8Array): ByteString {\n if (typeof blob === 'string') {\n return ByteString.fromBase64String(blob);\n } else {\n return ByteString.fromUint8Array(blob);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n Value as ProtoValue,\n MapValue as ProtoMapValue\n} from '../protos/firestore_proto_api';\n\nimport { normalizeTimestamp } from './normalize';\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\n\nconst SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';\nconst TYPE_KEY = '__type__';\nconst PREVIOUS_VALUE_KEY = '__previous_value__';\nconst LOCAL_WRITE_TIME_KEY = '__local_write_time__';\n\nexport function isServerTimestamp(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === SERVER_TIMESTAMP_SENTINEL;\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\nexport function serverTimestamp(\n localWriteTime: Timestamp,\n previousValue: ProtoValue | null\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: SERVER_TIMESTAMP_SENTINEL\n },\n [LOCAL_WRITE_TIME_KEY]: {\n timestampValue: {\n seconds: localWriteTime.seconds,\n nanos: localWriteTime.nanoseconds\n }\n }\n }\n };\n\n // We should avoid storing deeply nested server timestamp map values\n // because we never use the intermediate \"previous values\".\n // For example:\n // previous: 42L, add: t1, result: t1 -> 42L\n // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)\n // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)\n // `getPreviousValue` recursively traverses server timestamps to find the\n // least recent Value.\n if (previousValue && isServerTimestamp(previousValue)) {\n previousValue = getPreviousValue(previousValue);\n }\n if (previousValue) {\n mapValue.fields![PREVIOUS_VALUE_KEY] = previousValue;\n }\n\n return { mapValue };\n}\n\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nexport function getPreviousValue(value: ProtoValue): ProtoValue | null {\n const previousValue = value.mapValue!.fields![PREVIOUS_VALUE_KEY];\n\n if (isServerTimestamp(previousValue)) {\n return getPreviousValue(previousValue);\n }\n return previousValue;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */\nexport function getLocalWriteTime(value: ProtoValue): Timestamp {\n const localWriteTime = normalizeTimestamp(\n value.mapValue!.fields![LOCAL_WRITE_TIME_KEY].timestampValue!\n );\n return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);\n}\n","import { FirebaseApp } from '@firebase/app';\n\nimport { ExperimentalLongPollingOptions } from '../api/long_polling_options';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param longPollingOptions Options that configure long-polling.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly appId: string,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean,\n readonly autoDetectLongPolling: boolean,\n readonly longPollingOptions: ExperimentalLongPollingOptions,\n readonly useFetchStreams: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nexport const DEFAULT_DATABASE_NAME = '(default)';\n\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\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 static empty(): DatabaseId {\n return new DatabaseId('', '');\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\nexport function databaseIdFromApp(\n app: FirebaseApp,\n database?: string\n): DatabaseId {\n if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n return new DatabaseId(app.options.projectId!, database);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport {\n ArrayValue,\n LatLng,\n MapValue,\n Timestamp,\n Value\n} from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { arrayEquals, primitiveComparator } from '../util/misc';\nimport { forEach, objectSize } from '../util/obj';\nimport { isNegativeZero } from '../util/types';\n\nimport { DocumentKey } from './document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from './normalize';\nimport {\n getLocalWriteTime,\n getPreviousValue,\n isServerTimestamp\n} from './server_timestamps';\nimport { TypeOrder } from './type_order';\n\nconst MAX_VALUE_TYPE = '__max__';\nexport const MAX_VALUE: Value = {\n mapValue: {\n fields: {\n '__type__': { stringValue: MAX_VALUE_TYPE }\n }\n }\n};\n\nexport const MIN_VALUE: Value = {\n nullValue: 'NULL_VALUE'\n};\n\n/** Extracts the backend's type order for the provided value. */\nexport function typeOrder(value: Value): TypeOrder {\n if ('nullValue' in value) {\n return TypeOrder.NullValue;\n } else if ('booleanValue' in value) {\n return TypeOrder.BooleanValue;\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return TypeOrder.NumberValue;\n } else if ('timestampValue' in value) {\n return TypeOrder.TimestampValue;\n } else if ('stringValue' in value) {\n return TypeOrder.StringValue;\n } else if ('bytesValue' in value) {\n return TypeOrder.BlobValue;\n } else if ('referenceValue' in value) {\n return TypeOrder.RefValue;\n } else if ('geoPointValue' in value) {\n return TypeOrder.GeoPointValue;\n } else if ('arrayValue' in value) {\n return TypeOrder.ArrayValue;\n } else if ('mapValue' in value) {\n if (isServerTimestamp(value)) {\n return TypeOrder.ServerTimestampValue;\n } else if (isMaxValue(value)) {\n return TypeOrder.MaxValue;\n }\n return TypeOrder.ObjectValue;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */\nexport function valueEquals(left: Value, right: Value): boolean {\n if (left === right) {\n return true;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n if (leftType !== rightType) {\n return false;\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n return true;\n case TypeOrder.BooleanValue:\n return left.booleanValue === right.booleanValue;\n case TypeOrder.ServerTimestampValue:\n return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));\n case TypeOrder.TimestampValue:\n return timestampEquals(left, right);\n case TypeOrder.StringValue:\n return left.stringValue === right.stringValue;\n case TypeOrder.BlobValue:\n return blobEquals(left, right);\n case TypeOrder.RefValue:\n return left.referenceValue === right.referenceValue;\n case TypeOrder.GeoPointValue:\n return geoPointEquals(left, right);\n case TypeOrder.NumberValue:\n return numberEquals(left, right);\n case TypeOrder.ArrayValue:\n return arrayEquals(\n left.arrayValue!.values || [],\n right.arrayValue!.values || [],\n valueEquals\n );\n case TypeOrder.ObjectValue:\n return objectEquals(left, right);\n case TypeOrder.MaxValue:\n return true;\n default:\n return fail('Unexpected value type: ' + JSON.stringify(left));\n }\n}\n\nfunction timestampEquals(left: Value, right: Value): boolean {\n if (\n typeof left.timestampValue === 'string' &&\n typeof right.timestampValue === 'string' &&\n left.timestampValue.length === right.timestampValue.length\n ) {\n // Use string equality for ISO 8601 timestamps\n return left.timestampValue === right.timestampValue;\n }\n\n const leftTimestamp = normalizeTimestamp(left.timestampValue!);\n const rightTimestamp = normalizeTimestamp(right.timestampValue!);\n return (\n leftTimestamp.seconds === rightTimestamp.seconds &&\n leftTimestamp.nanos === rightTimestamp.nanos\n );\n}\n\nfunction geoPointEquals(left: Value, right: Value): boolean {\n return (\n normalizeNumber(left.geoPointValue!.latitude) ===\n normalizeNumber(right.geoPointValue!.latitude) &&\n normalizeNumber(left.geoPointValue!.longitude) ===\n normalizeNumber(right.geoPointValue!.longitude)\n );\n}\n\nfunction blobEquals(left: Value, right: Value): boolean {\n return normalizeByteString(left.bytesValue!).isEqual(\n normalizeByteString(right.bytesValue!)\n );\n}\n\nexport function numberEquals(left: Value, right: Value): boolean {\n if ('integerValue' in left && 'integerValue' in right) {\n return (\n normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)\n );\n } else if ('doubleValue' in left && 'doubleValue' in right) {\n const n1 = normalizeNumber(left.doubleValue!);\n const n2 = normalizeNumber(right.doubleValue!);\n\n if (n1 === n2) {\n return isNegativeZero(n1) === isNegativeZero(n2);\n } else {\n return isNaN(n1) && isNaN(n2);\n }\n }\n\n return false;\n}\n\nfunction objectEquals(left: Value, right: Value): boolean {\n const leftMap = left.mapValue!.fields || {};\n const rightMap = right.mapValue!.fields || {};\n\n if (objectSize(leftMap) !== objectSize(rightMap)) {\n return false;\n }\n\n for (const key in leftMap) {\n if (leftMap.hasOwnProperty(key)) {\n if (\n rightMap[key] === undefined ||\n !valueEquals(leftMap[key], rightMap[key])\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/** Returns true if the ArrayValue contains the specified element. */\nexport function arrayValueContains(\n haystack: ArrayValue,\n needle: Value\n): boolean {\n return (\n (haystack.values || []).find(v => valueEquals(v, needle)) !== undefined\n );\n}\n\nexport function valueCompare(left: Value, right: Value): number {\n if (left === right) {\n return 0;\n }\n\n const leftType = typeOrder(left);\n const rightType = typeOrder(right);\n\n if (leftType !== rightType) {\n return primitiveComparator(leftType, rightType);\n }\n\n switch (leftType) {\n case TypeOrder.NullValue:\n case TypeOrder.MaxValue:\n return 0;\n case TypeOrder.BooleanValue:\n return primitiveComparator(left.booleanValue!, right.booleanValue!);\n case TypeOrder.NumberValue:\n return compareNumbers(left, right);\n case TypeOrder.TimestampValue:\n return compareTimestamps(left.timestampValue!, right.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return compareTimestamps(\n getLocalWriteTime(left),\n getLocalWriteTime(right)\n );\n case TypeOrder.StringValue:\n return primitiveComparator(left.stringValue!, right.stringValue!);\n case TypeOrder.BlobValue:\n return compareBlobs(left.bytesValue!, right.bytesValue!);\n case TypeOrder.RefValue:\n return compareReferences(left.referenceValue!, right.referenceValue!);\n case TypeOrder.GeoPointValue:\n return compareGeoPoints(left.geoPointValue!, right.geoPointValue!);\n case TypeOrder.ArrayValue:\n return compareArrays(left.arrayValue!, right.arrayValue!);\n case TypeOrder.ObjectValue:\n return compareMaps(left.mapValue!, right.mapValue!);\n default:\n throw fail('Invalid value type: ' + leftType);\n }\n}\n\nfunction compareNumbers(left: Value, right: Value): number {\n const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);\n const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);\n\n if (leftNumber < rightNumber) {\n return -1;\n } else if (leftNumber > rightNumber) {\n return 1;\n } else if (leftNumber === rightNumber) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(leftNumber)) {\n return isNaN(rightNumber) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\nfunction compareTimestamps(left: Timestamp, right: Timestamp): number {\n if (\n typeof left === 'string' &&\n typeof right === 'string' &&\n left.length === right.length\n ) {\n return primitiveComparator(left, right);\n }\n\n const leftTimestamp = normalizeTimestamp(left);\n const rightTimestamp = normalizeTimestamp(right);\n\n const comparison = primitiveComparator(\n leftTimestamp.seconds,\n rightTimestamp.seconds\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);\n}\n\nfunction compareReferences(leftPath: string, rightPath: string): number {\n const leftSegments = leftPath.split('/');\n const rightSegments = rightPath.split('/');\n for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {\n const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(leftSegments.length, rightSegments.length);\n}\n\nfunction compareGeoPoints(left: LatLng, right: LatLng): number {\n const comparison = primitiveComparator(\n normalizeNumber(left.latitude),\n normalizeNumber(right.latitude)\n );\n if (comparison !== 0) {\n return comparison;\n }\n return primitiveComparator(\n normalizeNumber(left.longitude),\n normalizeNumber(right.longitude)\n );\n}\n\nfunction compareBlobs(\n left: string | Uint8Array,\n right: string | Uint8Array\n): number {\n const leftBytes = normalizeByteString(left);\n const rightBytes = normalizeByteString(right);\n return leftBytes.compareTo(rightBytes);\n}\n\nfunction compareArrays(left: ArrayValue, right: ArrayValue): number {\n const leftArray = left.values || [];\n const rightArray = right.values || [];\n\n for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {\n const compare = valueCompare(leftArray[i], rightArray[i]);\n if (compare) {\n return compare;\n }\n }\n return primitiveComparator(leftArray.length, rightArray.length);\n}\n\nfunction compareMaps(left: MapValue, right: MapValue): number {\n if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {\n return 0;\n } else if (left === MAX_VALUE.mapValue) {\n return 1;\n } else if (right === MAX_VALUE.mapValue) {\n return -1;\n }\n\n const leftMap = left.fields || {};\n const leftKeys = Object.keys(leftMap);\n const rightMap = right.fields || {};\n const rightKeys = Object.keys(rightMap);\n\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n leftKeys.sort();\n rightKeys.sort();\n\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {\n const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);\n if (keyCompare !== 0) {\n return keyCompare;\n }\n const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);\n if (compare !== 0) {\n return compare;\n }\n }\n\n return primitiveComparator(leftKeys.length, rightKeys.length);\n}\n\n/**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */\nexport function canonicalId(value: Value): string {\n return canonifyValue(value);\n}\n\nfunction canonifyValue(value: Value): string {\n if ('nullValue' in value) {\n return 'null';\n } else if ('booleanValue' in value) {\n return '' + value.booleanValue!;\n } else if ('integerValue' in value) {\n return '' + value.integerValue!;\n } else if ('doubleValue' in value) {\n return '' + value.doubleValue!;\n } else if ('timestampValue' in value) {\n return canonifyTimestamp(value.timestampValue!);\n } else if ('stringValue' in value) {\n return value.stringValue!;\n } else if ('bytesValue' in value) {\n return canonifyByteString(value.bytesValue!);\n } else if ('referenceValue' in value) {\n return canonifyReference(value.referenceValue!);\n } else if ('geoPointValue' in value) {\n return canonifyGeoPoint(value.geoPointValue!);\n } else if ('arrayValue' in value) {\n return canonifyArray(value.arrayValue!);\n } else if ('mapValue' in value) {\n return canonifyMap(value.mapValue!);\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction canonifyByteString(byteString: string | Uint8Array): string {\n return normalizeByteString(byteString).toBase64();\n}\n\nfunction canonifyTimestamp(timestamp: Timestamp): string {\n const normalizedTimestamp = normalizeTimestamp(timestamp);\n return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`;\n}\n\nfunction canonifyGeoPoint(geoPoint: LatLng): string {\n return `geo(${geoPoint.latitude},${geoPoint.longitude})`;\n}\n\nfunction canonifyReference(referenceValue: string): string {\n return DocumentKey.fromName(referenceValue).toString();\n}\n\nfunction canonifyMap(mapValue: MapValue): string {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const sortedKeys = Object.keys(mapValue.fields || {}).sort();\n\n let result = '{';\n let first = true;\n for (const key of sortedKeys) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += `${key}:${canonifyValue(mapValue.fields![key])}`;\n }\n return result + '}';\n}\n\nfunction canonifyArray(arrayValue: ArrayValue): string {\n let result = '[';\n let first = true;\n for (const value of arrayValue.values || []) {\n if (!first) {\n result += ',';\n } else {\n first = false;\n }\n result += canonifyValue(value);\n }\n return result + ']';\n}\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 */\nexport function estimateByteSize(value: Value): number {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return 4;\n case TypeOrder.BooleanValue:\n return 4;\n case TypeOrder.NumberValue:\n return 8;\n case TypeOrder.TimestampValue:\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n case TypeOrder.ServerTimestampValue:\n const previousValue = getPreviousValue(value);\n return previousValue ? 16 + estimateByteSize(previousValue) : 16;\n case TypeOrder.StringValue:\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 value.stringValue!.length * 2;\n case TypeOrder.BlobValue:\n return normalizeByteString(value.bytesValue!).approximateByteSize();\n case TypeOrder.RefValue:\n return value.referenceValue!.length;\n case TypeOrder.GeoPointValue:\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n case TypeOrder.ArrayValue:\n return estimateArrayByteSize(value.arrayValue!);\n case TypeOrder.ObjectValue:\n return estimateMapByteSize(value.mapValue!);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nfunction estimateMapByteSize(mapValue: MapValue): number {\n let size = 0;\n forEach(mapValue.fields, (key, val) => {\n size += key.length + estimateByteSize(val);\n });\n return size;\n}\n\nfunction estimateArrayByteSize(arrayValue: ArrayValue): number {\n return (arrayValue.values || []).reduce(\n (previousSize, value) => previousSize + estimateByteSize(value),\n 0\n );\n}\n\n/** Returns a reference value for the provided database and key. */\nexport function refValue(databaseId: DatabaseId, key: DocumentKey): Value {\n return {\n referenceValue: `projects/${databaseId.projectId}/databases/${\n databaseId.database\n }/documents/${key.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */\nexport function isInteger(\n value?: Value | null\n): value is { integerValue: string | number } {\n return !!value && 'integerValue' in value;\n}\n\n/** Returns true if `value` is a DoubleValue. */\nexport function isDouble(\n value?: Value | null\n): value is { doubleValue: string | number } {\n return !!value && 'doubleValue' in value;\n}\n\n/** Returns true if `value` is either an IntegerValue or a DoubleValue. */\nexport function isNumber(value?: Value | null): boolean {\n return isInteger(value) || isDouble(value);\n}\n\n/** Returns true if `value` is an ArrayValue. */\nexport function isArray(\n value?: Value | null\n): value is { arrayValue: ArrayValue } {\n return !!value && 'arrayValue' in value;\n}\n\n/** Returns true if `value` is a ReferenceValue. */\nexport function isReferenceValue(\n value?: Value | null\n): value is { referenceValue: string } {\n return !!value && 'referenceValue' in value;\n}\n\n/** Returns true if `value` is a NullValue. */\nexport function isNullValue(\n value?: Value | null\n): value is { nullValue: 'NULL_VALUE' } {\n return !!value && 'nullValue' in value;\n}\n\n/** Returns true if `value` is NaN. */\nexport function isNanValue(\n value?: Value | null\n): value is { doubleValue: 'NaN' | number } {\n return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */\nexport function isMapValue(\n value?: Value | null\n): value is { mapValue: MapValue } {\n return !!value && 'mapValue' in value;\n}\n\n/** Creates a deep copy of `source`. */\nexport function deepClone(source: Value): Value {\n if (source.geoPointValue) {\n return { geoPointValue: { ...source.geoPointValue } };\n } else if (\n source.timestampValue &&\n typeof source.timestampValue === 'object'\n ) {\n return { timestampValue: { ...source.timestampValue } };\n } else if (source.mapValue) {\n const target: Value = { mapValue: { fields: {} } };\n forEach(\n source.mapValue.fields,\n (key, val) => (target.mapValue!.fields![key] = deepClone(val))\n );\n return target;\n } else if (source.arrayValue) {\n const target: Value = { arrayValue: { values: [] } };\n for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {\n target.arrayValue!.values![i] = deepClone(source.arrayValue.values![i]);\n }\n return target;\n } else {\n return { ...source };\n }\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */\nexport function isMaxValue(value: Value): boolean {\n return (\n (((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===\n MAX_VALUE_TYPE\n );\n}\n\n/** Returns the lowest value for the given value type (inclusive). */\nexport function valuesGetLowerBound(value: Value): Value {\n if ('nullValue' in value) {\n return MIN_VALUE;\n } else if ('booleanValue' in value) {\n return { booleanValue: false };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { doubleValue: NaN };\n } else if ('timestampValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('stringValue' in value) {\n return { stringValue: '' };\n } else if ('bytesValue' in value) {\n return { bytesValue: '' };\n } else if ('referenceValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('geoPointValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('arrayValue' in value) {\n return { arrayValue: {} };\n } else if ('mapValue' in value) {\n return { mapValue: {} };\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\n/** Returns the largest value for the given value type (exclusive). */\nexport function valuesGetUpperBound(value: Value): Value {\n if ('nullValue' in value) {\n return { booleanValue: false };\n } else if ('booleanValue' in value) {\n return { doubleValue: NaN };\n } else if ('integerValue' in value || 'doubleValue' in value) {\n return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } };\n } else if ('timestampValue' in value) {\n return { stringValue: '' };\n } else if ('stringValue' in value) {\n return { bytesValue: '' };\n } else if ('bytesValue' in value) {\n return refValue(DatabaseId.empty(), DocumentKey.empty());\n } else if ('referenceValue' in value) {\n return { geoPointValue: { latitude: -90, longitude: -180 } };\n } else if ('geoPointValue' in value) {\n return { arrayValue: {} };\n } else if ('arrayValue' in value) {\n return { mapValue: {} };\n } else if ('mapValue' in value) {\n return MAX_VALUE;\n } else {\n return fail('Invalid value type: ' + JSON.stringify(value));\n }\n}\n\nexport function lowerBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return -1;\n } else if (!left.inclusive && right.inclusive) {\n return 1;\n }\n\n return 0;\n}\n\nexport function upperBoundCompare(\n left: { value: Value; inclusive: boolean },\n right: { value: Value; inclusive: boolean }\n): number {\n const cmp = valueCompare(left.value, right.value);\n if (cmp !== 0) {\n return cmp;\n }\n\n if (left.inclusive && !right.inclusive) {\n return 1;\n } else if (!left.inclusive && right.inclusive) {\n return -1;\n }\n\n return 0;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\nimport { forEach } from '../util/obj';\n\nimport { FieldMask } from './field_mask';\nimport { FieldPath } from './path';\nimport { isServerTimestamp } from './server_timestamps';\nimport { deepClone, isMapValue, valueEquals } from './values';\n\nexport interface JsonObject<T> {\n [name: string]: T;\n}\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */\nexport class ObjectValue {\n constructor(readonly value: { mapValue: ProtoMapValue }) {\n debugAssert(\n !isServerTimestamp(value),\n 'ServerTimestamps should be converted to ServerTimestampValue'\n );\n }\n\n static empty(): ObjectValue {\n return new ObjectValue({ mapValue: {} });\n }\n\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */\n field(path: FieldPath): ProtoValue | null {\n if (path.isEmpty()) {\n return this.value;\n } else {\n let currentLevel: ProtoValue = this.value;\n for (let i = 0; i < path.length - 1; ++i) {\n currentLevel = (currentLevel.mapValue!.fields || {})[path.get(i)];\n if (!isMapValue(currentLevel)) {\n return null;\n }\n }\n currentLevel = (currentLevel.mapValue!.fields! || {})[path.lastSegment()];\n return currentLevel || null;\n }\n }\n\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */\n set(path: FieldPath, value: ProtoValue): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot set field for empty path on ObjectValue'\n );\n const fieldsMap = this.getFieldsMap(path.popLast());\n fieldsMap[path.lastSegment()] = deepClone(value);\n }\n\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */\n setAll(data: Map<FieldPath, ProtoValue | null>): void {\n let parent = FieldPath.emptyPath();\n\n let upserts: { [key: string]: ProtoValue } = {};\n let deletes: string[] = [];\n\n data.forEach((value, path) => {\n if (!parent.isImmediateParentOf(path)) {\n // Insert the accumulated changes at this parent location\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n upserts = {};\n deletes = [];\n parent = path.popLast();\n }\n\n if (value) {\n upserts[path.lastSegment()] = deepClone(value);\n } else {\n deletes.push(path.lastSegment());\n }\n });\n\n const fieldsMap = this.getFieldsMap(parent);\n this.applyChanges(fieldsMap, upserts, deletes);\n }\n\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */\n delete(path: FieldPath): void {\n debugAssert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const nestedValue = this.field(path.popLast());\n if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {\n delete nestedValue.mapValue.fields[path.lastSegment()];\n }\n }\n\n isEqual(other: ObjectValue): boolean {\n return valueEquals(this.value, other.value);\n }\n\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */\n private getFieldsMap(path: FieldPath): Record<string, ProtoValue> {\n let current = this.value;\n\n if (!current.mapValue!.fields) {\n current.mapValue = { fields: {} };\n }\n\n for (let i = 0; i < path.length; ++i) {\n let next = current.mapValue!.fields![path.get(i)];\n if (!isMapValue(next) || !next.mapValue.fields) {\n next = { mapValue: { fields: {} } };\n current.mapValue!.fields![path.get(i)] = next;\n }\n current = next as { mapValue: ProtoMapValue };\n }\n\n return current.mapValue!.fields!;\n }\n\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */\n private applyChanges(\n fieldsMap: Record<string, ProtoValue>,\n inserts: { [key: string]: ProtoValue },\n deletes: string[]\n ): void {\n forEach(inserts, (key, val) => (fieldsMap[key] = val));\n for (const field of deletes) {\n delete fieldsMap[field];\n }\n }\n\n clone(): ObjectValue {\n return new ObjectValue(\n deepClone(this.value) as { mapValue: ProtoMapValue }\n );\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */\nexport function extractFieldMask(value: ProtoMapValue): FieldMask {\n const fields: FieldPath[] = [];\n forEach(value!.fields, (key, value) => {\n const currentPath = new FieldPath([key]);\n if (isMapValue(value)) {\n const nestedMask = extractFieldMask(value.mapValue!);\n const nestedFields = nestedMask.fields;\n if (nestedFields.length === 0) {\n // Preserve the empty map by adding it to the FieldMask.\n fields.push(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const nestedPath of nestedFields) {\n fields.push(currentPath.child(nestedPath));\n }\n }\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n fields.push(currentPath);\n }\n });\n return new FieldMask(fields);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport { valueCompare } from './values';\n\n/**\n * Whether the document represents an existing document, a document that is\n * known to exist or a document whose state or existence is unknown.\n */\nconst enum DocumentType {\n /**\n * Represents the initial state of a MutableDocument when only the document\n * key is known. Invalid documents transition to other states as mutations are\n * applied. If a document remains invalid after applying mutations, it should\n * be discarded.\n *\n * Invalid documents can have neither local nor committed mutations.\n */\n INVALID,\n /**\n * Represents a document in Firestore with a key, version, data and whether\n * the data has local mutations applied to it.\n *\n * Found documents can be sycned or have or committed mutations applied.\n */\n FOUND_DOCUMENT,\n /**\n * Represents that no documents exists for the key at the given version.\n *\n * Documents that are deleted based on a local mutation do not raise snapshots\n * with `hasPendingWrites`. As such, deleted documents never have\n * `HAS_LOCAL_MUTATIONS` set. Once a delete is committed, we store them with\n * `HAS_COMMITTED_MUTATIONS` until we received the delete from the Watch\n * stream.\n */\n NO_DOCUMENT,\n /**\n * Represents an existing document whose data is unknown (e.g. a document that\n * was updated without a known base document).\n *\n * An unknown document always has `HAS_COMMITTED_MUTATIONS` set, since unknown\n * documents can only be generated by applying a patch mutation from a write\n * acknowledgement.\n */\n UNKNOWN_DOCUMENT\n}\n\n/** Describes whether a document has latency-compensated edits applied. */\nconst enum DocumentState {\n /** No mutations applied. Document was sent to us by Watch. */\n SYNCED,\n /**\n * Local mutations applied via the mutation queue. Document is potentially\n * inconsistent.\n */\n HAS_LOCAL_MUTATIONS,\n /**\n * Mutations applied based on a write acknowledgment. Document is potentially\n * inconsistent.\n */\n HAS_COMMITTED_MUTATIONS\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 interface Document {\n /** The key for this document */\n readonly key: DocumentKey;\n\n /**\n * The version of this document if it exists or a version at which this\n * document was guaranteed to not exist.\n */\n readonly version: SnapshotVersion;\n\n /**\n * The timestamp at which this document was read from the remote server. Uses\n * `SnapshotVersion.min()` for documents created by the user.\n */\n readonly readTime: SnapshotVersion;\n\n /**\n * The timestamp at which the document was created. This value increases\n * monotonically when a document is deleted then recreated. It can also be\n * compared to `createTime` of other documents and the `readTime` of a query.\n */\n readonly createTime: SnapshotVersion;\n\n /** The underlying data of this document or an empty value if no data exists. */\n readonly data: ObjectValue;\n\n /** Returns whether local mutations were applied via the mutation queue. */\n readonly hasLocalMutations: boolean;\n\n /** Returns whether mutations were applied based on a write acknowledgment. */\n readonly hasCommittedMutations: boolean;\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * Returns whether this document is valid (i.e. it is an entry in the\n * RemoteDocumentCache, was created by a mutation or read from the backend).\n */\n isValidDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is known at the current\n * version.\n */\n isFoundDocument(): boolean;\n\n /**\n * Returns whether the document is known to not exist at the current version.\n */\n isNoDocument(): boolean;\n\n /**\n * Returns whether the document exists and its data is unknown at the current\n * version.\n */\n isUnknownDocument(): boolean;\n\n isEqual(other: Document | null | undefined): boolean;\n\n /** Creates a mutable copy of this document. */\n mutableCopy(): MutableDocument;\n\n toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */\nexport class MutableDocument implements Document {\n private constructor(\n readonly key: DocumentKey,\n private documentType: DocumentType,\n public version: SnapshotVersion,\n public readTime: SnapshotVersion,\n public createTime: SnapshotVersion,\n public data: ObjectValue,\n private documentState: DocumentState\n ) {}\n\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */\n static newInvalidDocument(documentKey: DocumentKey): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.INVALID,\n /* version */ SnapshotVersion.min(),\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */\n static newFoundDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion,\n createTime: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.FOUND_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ createTime,\n value,\n DocumentState.SYNCED\n );\n }\n\n /** Creates a new document that is known to not exist at the given version. */\n static newNoDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.NO_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.SYNCED\n );\n }\n\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */\n static newUnknownDocument(\n documentKey: DocumentKey,\n version: SnapshotVersion\n ): MutableDocument {\n return new MutableDocument(\n documentKey,\n DocumentType.UNKNOWN_DOCUMENT,\n /* version */ version,\n /* readTime */ SnapshotVersion.min(),\n /* createTime */ SnapshotVersion.min(),\n ObjectValue.empty(),\n DocumentState.HAS_COMMITTED_MUTATIONS\n );\n }\n\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */\n convertToFoundDocument(\n version: SnapshotVersion,\n value: ObjectValue\n ): MutableDocument {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n if (\n this.createTime.isEqual(SnapshotVersion.min()) &&\n (this.documentType === DocumentType.NO_DOCUMENT ||\n this.documentType === DocumentType.INVALID)\n ) {\n this.createTime = version;\n }\n this.version = version;\n this.documentType = DocumentType.FOUND_DOCUMENT;\n this.data = value;\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */\n convertToNoDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.NO_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.SYNCED;\n return this;\n }\n\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */\n convertToUnknownDocument(version: SnapshotVersion): MutableDocument {\n this.version = version;\n this.documentType = DocumentType.UNKNOWN_DOCUMENT;\n this.data = ObjectValue.empty();\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasCommittedMutations(): MutableDocument {\n debugAssert(\n this.isValidDocument(),\n 'Invalid documents cannot have committed mutations'\n );\n this.documentState = DocumentState.HAS_COMMITTED_MUTATIONS;\n return this;\n }\n\n setHasLocalMutations(): MutableDocument {\n this.documentState = DocumentState.HAS_LOCAL_MUTATIONS;\n this.version = SnapshotVersion.min();\n return this;\n }\n\n setReadTime(readTime: SnapshotVersion): MutableDocument {\n this.readTime = readTime;\n return this;\n }\n\n get hasLocalMutations(): boolean {\n return this.documentState === DocumentState.HAS_LOCAL_MUTATIONS;\n }\n\n get hasCommittedMutations(): boolean {\n return this.documentState === DocumentState.HAS_COMMITTED_MUTATIONS;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n isValidDocument(): boolean {\n return this.documentType !== DocumentType.INVALID;\n }\n\n isFoundDocument(): boolean {\n return this.documentType === DocumentType.FOUND_DOCUMENT;\n }\n\n isNoDocument(): boolean {\n return this.documentType === DocumentType.NO_DOCUMENT;\n }\n\n isUnknownDocument(): boolean {\n return this.documentType === DocumentType.UNKNOWN_DOCUMENT;\n }\n\n isEqual(other: Document | null | undefined): boolean {\n return (\n other instanceof MutableDocument &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.documentType === other.documentType &&\n this.documentState === other.documentState &&\n this.data.isEqual(other.data)\n );\n }\n\n mutableCopy(): MutableDocument {\n return new MutableDocument(\n this.key,\n this.documentType,\n this.version,\n this.readTime,\n this.createTime,\n this.data.clone(),\n this.documentState\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${JSON.stringify(\n this.data.value\n )}, ` +\n `{createTime: ${this.createTime}}), ` +\n `{documentType: ${this.documentType}}), ` +\n `{documentState: ${this.documentState}})`\n );\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\nexport function compareDocumentsByField(\n field: FieldPath,\n d1: Document,\n d2: Document\n): number {\n const v1 = d1.data.field(field);\n const v2 = d2.data.field(field);\n if (v1 !== null && v2 !== null) {\n return valueCompare(v1, v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { isReferenceValue, valueCompare, valueEquals } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert } from '../util/assert';\n\nimport { Direction, OrderBy } from './order_by';\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: ProtoValue[], readonly inclusive: boolean) {}\n}\n\nfunction boundCompareToDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): number {\n debugAssert(\n bound.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < bound.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = bound.position[i];\n if (orderByComponent.field.isKeyField()) {\n debugAssert(\n isReferenceValue(component),\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(\n DocumentKey.fromName(component.referenceValue),\n doc.key\n );\n } else {\n const docValue = doc.data.field(orderByComponent.field);\n debugAssert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = valueCompare(component, docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return comparison;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */\nexport function boundSortsAfterDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison >= 0 : comparison > 0;\n}\n\n/**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\nexport function boundSortsBeforeDocument(\n bound: Bound,\n orderBy: OrderBy[],\n doc: Document\n): boolean {\n const comparison = boundCompareToDocument(bound, orderBy, doc);\n return bound.inclusive ? comparison <= 0 : comparison < 0;\n}\n\nexport function boundEquals(left: Bound | null, right: Bound | null): boolean {\n if (left === null) {\n return right === null;\n } else if (right === null) {\n return false;\n }\n\n if (\n left.inclusive !== right.inclusive ||\n left.position.length !== right.position.length\n ) {\n return false;\n }\n for (let i = 0; i < left.position.length; i++) {\n const leftPosition = left.position[i];\n const rightPosition = right.position[i];\n if (!valueEquals(leftPosition, rightPosition)) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from '../model/path';\n\n/**\n * The direction of sorting in an order by.\n */\nexport const enum Direction {\n ASCENDING = 'asc',\n DESCENDING = 'desc'\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n constructor(\n readonly field: FieldPath,\n readonly dir: Direction = Direction.ASCENDING\n ) {}\n}\n\nexport function canonifyOrderBy(orderBy: OrderBy): string {\n // TODO(b/29183165): Make this collision robust.\n return orderBy.field.canonicalString() + orderBy.dir;\n}\n\nexport function stringifyOrderBy(orderBy: OrderBy): string {\n return `${orderBy.field.canonicalString()} (${orderBy.dir})`;\n}\n\nexport function orderByEquals(left: OrderBy, right: OrderBy): boolean {\n return left.dir === right.dir && left.field.isEqual(right.field);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath } from '../model/path';\nimport {\n arrayValueContains,\n canonicalId,\n isArray,\n isReferenceValue,\n typeOrder,\n valueCompare,\n valueEquals\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail } from '../util/assert';\n\n// The operator of a FieldFilter\nexport const enum Operator {\n LESS_THAN = '<',\n LESS_THAN_OR_EQUAL = '<=',\n EQUAL = '==',\n NOT_EQUAL = '!=',\n GREATER_THAN = '>',\n GREATER_THAN_OR_EQUAL = '>=',\n ARRAY_CONTAINS = 'array-contains',\n IN = 'in',\n NOT_IN = 'not-in',\n ARRAY_CONTAINS_ANY = 'array-contains-any'\n}\n\n// The operator of a CompositeFilter\nexport const enum CompositeOperator {\n OR = 'or',\n AND = 'and'\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n\n abstract getFlattenedFilters(): readonly FieldFilter[];\n\n abstract getFilters(): Filter[];\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public readonly field: FieldPath,\n public readonly op: Operator,\n public readonly value: ProtoValue\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: ProtoValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN || op === Operator.NOT_IN) {\n return this.createKeyFieldInFilter(field, op, value);\n } else {\n debugAssert(\n isReferenceValue(value),\n 'Comparing on key, but filter value not a RefValue'\n );\n debugAssert(\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 (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n debugAssert(\n isArray(value),\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.NOT_IN) {\n debugAssert(\n isArray(value),\n 'NOT_IN filter has invalid value: ' + value.toString()\n );\n return new NotInFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n debugAssert(\n isArray(value),\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 private static createKeyFieldInFilter(\n field: FieldPath,\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n ): FieldFilter {\n debugAssert(\n isArray(value),\n `Comparing on key with ${op.toString()}` +\n ', but filter value not an ArrayValue'\n );\n debugAssert(\n (value.arrayValue.values || []).every(elem => isReferenceValue(elem)),\n `Comparing on key with ${op.toString()}` +\n ', but an array value was not a RefValue'\n );\n\n return op === Operator.IN\n ? new KeyFieldInFilter(field, value)\n : new KeyFieldNotInFilter(field, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n if (this.op === Operator.NOT_EQUAL) {\n return (\n other !== null &&\n this.matchesComparison(valueCompare(other!, this.value))\n );\n }\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n typeOrder(this.value) === typeOrder(other) &&\n this.matchesComparison(valueCompare(other, 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.NOT_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 Operator.NOT_EQUAL,\n Operator.NOT_IN\n ].indexOf(this.op) >= 0\n );\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n return [this];\n }\n\n getFilters(): Filter[] {\n return [this];\n }\n}\n\nexport class CompositeFilter extends Filter {\n private memoizedFlattenedFilters: FieldFilter[] | null = null;\n\n protected constructor(\n public readonly filters: readonly Filter[],\n public readonly op: CompositeOperator\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(filters: Filter[], op: CompositeOperator): CompositeFilter {\n return new CompositeFilter(filters, op);\n }\n\n matches(doc: Document): boolean {\n if (compositeFilterIsConjunction(this)) {\n // For conjunctions, all filters must match, so return false if any filter doesn't match.\n return this.filters.find(filter => !filter.matches(doc)) === undefined;\n } else {\n // For disjunctions, at least one filter should match.\n return this.filters.find(filter => filter.matches(doc)) !== undefined;\n }\n }\n\n getFlattenedFilters(): readonly FieldFilter[] {\n if (this.memoizedFlattenedFilters !== null) {\n return this.memoizedFlattenedFilters;\n }\n\n this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {\n return result.concat(subfilter.getFlattenedFilters());\n }, [] as FieldFilter[]);\n\n return this.memoizedFlattenedFilters;\n }\n\n // Returns a mutable copy of `this.filters`\n getFilters(): Filter[] {\n return Object.assign([], this.filters);\n }\n}\n\nexport function compositeFilterIsConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.AND;\n}\n\nexport function compositeFilterIsDisjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return compositeFilter.op === CompositeOperator.OR;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */\nexport function compositeFilterIsFlatConjunction(\n compositeFilter: CompositeFilter\n): boolean {\n return (\n compositeFilterIsFlat(compositeFilter) &&\n compositeFilterIsConjunction(compositeFilter)\n );\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */\nexport function compositeFilterIsFlat(\n compositeFilter: CompositeFilter\n): boolean {\n for (const filter of compositeFilter.filters) {\n if (filter instanceof CompositeFilter) {\n return false;\n }\n }\n return true;\n}\n\nexport function canonifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'canonifyFilter() only supports FieldFilters and CompositeFilters'\n );\n\n if (filter instanceof FieldFilter) {\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 filter.field.canonicalString() +\n filter.op.toString() +\n canonicalId(filter.value)\n );\n } else if (compositeFilterIsFlatConjunction(filter)) {\n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return filter.filters.map(filter => canonifyFilter(filter)).join(',');\n } else {\n // filter instanceof CompositeFilter\n const canonicalIdsString = filter.filters\n .map(filter => canonifyFilter(filter))\n .join(',');\n return `${filter.op}(${canonicalIdsString})`;\n }\n}\n\nexport function filterEquals(f1: Filter, f2: Filter): boolean {\n if (f1 instanceof FieldFilter) {\n return fieldFilterEquals(f1, f2);\n } else if (f1 instanceof CompositeFilter) {\n return compositeFilterEquals(f1, f2);\n } else {\n fail('Only FieldFilters and CompositeFilters can be compared');\n }\n}\n\nexport function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean {\n return (\n f2 instanceof FieldFilter &&\n f1.op === f2.op &&\n f1.field.isEqual(f2.field) &&\n valueEquals(f1.value, f2.value)\n );\n}\n\nexport function compositeFilterEquals(\n f1: CompositeFilter,\n f2: Filter\n): boolean {\n if (\n f2 instanceof CompositeFilter &&\n f1.op === f2.op &&\n f1.filters.length === f2.filters.length\n ) {\n const subFiltersMatch: boolean = f1.filters.reduce(\n (result: boolean, f1Filter: Filter, index: number): boolean =>\n result && filterEquals(f1Filter, f2.filters[index]),\n true\n );\n\n return subFiltersMatch;\n }\n\n return false;\n}\n\n/**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */\nexport function compositeFilterWithAddedFilters(\n compositeFilter: CompositeFilter,\n otherFilters: Filter[]\n): CompositeFilter {\n const mergedFilters = compositeFilter.filters.concat(otherFilters);\n return CompositeFilter.create(mergedFilters, compositeFilter.op);\n}\n\n/** Returns a debug description for `filter`. */\nexport function stringifyFilter(filter: Filter): string {\n debugAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'stringifyFilter() only supports FieldFilters and CompositeFilters'\n );\n if (filter instanceof FieldFilter) {\n return stringifyFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return stringifyCompositeFilter(filter);\n } else {\n return 'Filter';\n }\n}\n\nexport function stringifyCompositeFilter(filter: CompositeFilter): string {\n return (\n filter.op.toString() +\n ` {` +\n filter.getFilters().map(stringifyFilter).join(' ,') +\n '}'\n );\n}\n\nexport function stringifyFieldFilter(filter: FieldFilter): string {\n return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(\n filter.value\n )}`;\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n private readonly key: DocumentKey;\n\n constructor(field: FieldPath, op: Operator, value: ProtoValue) {\n super(field, op, value);\n debugAssert(\n isReferenceValue(value),\n 'KeyFieldFilter expects a ReferenceValue'\n );\n this.key = DocumentKey.fromName(value.referenceValue);\n }\n\n matches(doc: Document): boolean {\n const comparison = DocumentKey.comparator(doc.key, this.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 private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n return this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */\nexport class KeyFieldNotInFilter extends FieldFilter {\n private readonly keys: DocumentKey[];\n\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value);\n }\n\n matches(doc: Document): boolean {\n return !this.keys.some(key => key.isEqual(doc.key));\n }\n}\n\nfunction extractDocumentKeysFromArrayValue(\n op: Operator.IN | Operator.NOT_IN,\n value: ProtoValue\n): DocumentKey[] {\n debugAssert(\n isArray(value),\n 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue'\n );\n return (value.arrayValue?.values || []).map(v => {\n debugAssert(\n isReferenceValue(v),\n `Comparing on key with ${op.toString()}, but an array value was not ` +\n `a ReferenceValue`\n );\n return DocumentKey.fromName(v.referenceValue);\n });\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return isArray(other) && arrayValueContains(other.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.IN, value);\n debugAssert(isArray(value), 'InFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n return other !== null && arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the not-in operator. */\nexport class NotInFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.NOT_IN, value);\n debugAssert(isArray(value), 'NotInFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n if (\n arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' })\n ) {\n return false;\n }\n const other = doc.data.field(this.field);\n return other !== null && !arrayValueContains(this.value.arrayValue!, other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, value: ProtoValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue');\n }\n\n matches(doc: Document): boolean {\n const other = doc.data.field(this.field);\n if (!isArray(other) || !other.arrayValue.values) {\n return false;\n }\n return other.arrayValue.values.some(val =>\n arrayValueContains(this.value.arrayValue!, val)\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n canonicalId,\n MAX_VALUE,\n MIN_VALUE,\n lowerBoundCompare,\n upperBoundCompare,\n valuesGetLowerBound,\n valuesGetUpperBound\n} from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugCast } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Bound, boundEquals } from './bound';\nimport {\n Filter,\n FieldFilter,\n canonifyFilter,\n stringifyFilter,\n filterEquals,\n Operator\n} from './filter';\nimport {\n canonifyOrderBy,\n OrderBy,\n orderByEquals,\n stringifyOrderBy\n} from './order_by';\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 interface Target {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly orderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\n}\n\n// Visible for testing\nexport class TargetImpl implements Target {\n memoizedCanonicalId: string | null = null;\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\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */\nexport function newTarget(\n path: ResourcePath,\n collectionGroup: string | null = null,\n orderBy: OrderBy[] = [],\n filters: Filter[] = [],\n limit: number | null = null,\n startAt: Bound | null = null,\n endAt: Bound | null = null\n): Target {\n return new TargetImpl(\n path,\n collectionGroup,\n orderBy,\n filters,\n limit,\n startAt,\n endAt\n );\n}\n\nexport function canonifyTarget(target: Target): string {\n const targetImpl = debugCast(target, TargetImpl);\n\n if (targetImpl.memoizedCanonicalId === null) {\n let str = targetImpl.path.canonicalString();\n if (targetImpl.collectionGroup !== null) {\n str += '|cg:' + targetImpl.collectionGroup;\n }\n str += '|f:';\n str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');\n str += '|ob:';\n str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');\n\n if (!isNullOrUndefined(targetImpl.limit)) {\n str += '|l:';\n str += targetImpl.limit!;\n }\n if (targetImpl.startAt) {\n str += '|lb:';\n str += targetImpl.startAt.inclusive ? 'b:' : 'a:';\n str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (targetImpl.endAt) {\n str += '|ub:';\n str += targetImpl.endAt.inclusive ? 'a:' : 'b:';\n str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');\n }\n targetImpl.memoizedCanonicalId = str;\n }\n return targetImpl.memoizedCanonicalId;\n}\n\nexport function stringifyTarget(target: Target): string {\n let str = target.path.canonicalString();\n if (target.collectionGroup !== null) {\n str += ' collectionGroup=' + target.collectionGroup;\n }\n if (target.filters.length > 0) {\n str += `, filters: [${target.filters\n .map(f => stringifyFilter(f))\n .join(', ')}]`;\n }\n if (!isNullOrUndefined(target.limit)) {\n str += ', limit: ' + target.limit;\n }\n if (target.orderBy.length > 0) {\n str += `, orderBy: [${target.orderBy\n .map(o => stringifyOrderBy(o))\n .join(', ')}]`;\n }\n if (target.startAt) {\n str += ', startAt: ';\n str += target.startAt.inclusive ? 'b:' : 'a:';\n str += target.startAt.position.map(p => canonicalId(p)).join(',');\n }\n if (target.endAt) {\n str += ', endAt: ';\n str += target.endAt.inclusive ? 'a:' : 'b:';\n str += target.endAt.position.map(p => canonicalId(p)).join(',');\n }\n return `Target(${str})`;\n}\n\nexport function targetEquals(left: Target, right: Target): boolean {\n if (left.limit !== right.limit) {\n return false;\n }\n\n if (left.orderBy.length !== right.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < left.orderBy.length; i++) {\n if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {\n return false;\n }\n }\n\n if (left.filters.length !== right.filters.length) {\n return false;\n }\n\n for (let i = 0; i < left.filters.length; i++) {\n if (!filterEquals(left.filters[i], right.filters[i])) {\n return false;\n }\n }\n\n if (left.collectionGroup !== right.collectionGroup) {\n return false;\n }\n\n if (!left.path.isEqual(right.path)) {\n return false;\n }\n\n if (!boundEquals(left.startAt, right.startAt)) {\n return false;\n }\n\n return boundEquals(left.endAt, right.endAt);\n}\n\nexport function targetIsDocumentTarget(target: Target): boolean {\n return (\n DocumentKey.isDocumentKey(target.path) &&\n target.collectionGroup === null &&\n target.filters.length === 0\n );\n}\n\n/** Returns the field filters that target the given field path. */\nexport function targetGetFieldFiltersForPath(\n target: Target,\n path: FieldPath\n): FieldFilter[] {\n return target.filters.filter(\n f => f instanceof FieldFilter && f.field.isEqual(path)\n ) as FieldFilter[];\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\nexport function targetGetArrayValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const segment = fieldIndexGetArraySegment(fieldIndex);\n if (segment === undefined) {\n return null;\n }\n\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.ARRAY_CONTAINS_ANY:\n return fieldFilter.value.arrayValue!.values || [];\n case Operator.ARRAY_CONTAINS:\n return [fieldFilter.value];\n default:\n // Remaining filters are not array filters.\n }\n }\n return null;\n}\n\n/**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */\nexport function targetGetNotInValues(\n target: Target,\n fieldIndex: FieldIndex\n): ProtoValue[] | null {\n const values = new Map</* fieldPath = */ string, ProtoValue>();\n\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n for (const fieldFilter of targetGetFieldFiltersForPath(\n target,\n segment.fieldPath\n )) {\n switch (fieldFilter.op) {\n case Operator.EQUAL:\n case Operator.IN:\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n break;\n case Operator.NOT_IN:\n case Operator.NOT_EQUAL:\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n values.set(segment.fieldPath.canonicalString(), fieldFilter.value);\n return Array.from(values.values());\n default:\n // Remaining filters cannot be used as notIn bounds.\n }\n }\n }\n\n return null;\n}\n\n/**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */\nexport function targetGetLowerBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)\n : targetGetDescendingBound(target, segment.fieldPath, target.startAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */\nexport function targetGetUpperBound(\n target: Target,\n fieldIndex: FieldIndex\n): Bound {\n const values: ProtoValue[] = [];\n let inclusive = true;\n\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const segmentBound =\n segment.kind === IndexKind.ASCENDING\n ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)\n : targetGetAscendingBound(target, segment.fieldPath, target.endAt);\n\n values.push(segmentBound.value);\n inclusive &&= segmentBound.inclusive;\n }\n\n return new Bound(values, inclusive);\n}\n\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction targetGetAscendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MIN_VALUE;\n\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MIN_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.LESS_THAN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = valuesGetLowerBound(fieldFilter.value);\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.GREATER_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.GREATER_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MIN_VALUE;\n break;\n default:\n // Remaining filters cannot be used as lower bounds.\n }\n\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) < 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n lowerBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) < 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */\nfunction targetGetDescendingBound(\n target: Target,\n fieldPath: FieldPath,\n bound: Bound | null\n): { value: ProtoValue; inclusive: boolean } {\n let value: ProtoValue = MAX_VALUE;\n let inclusive = true;\n\n // Process all filters to find a value for the current field segment\n for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {\n let filterValue: ProtoValue = MAX_VALUE;\n let filterInclusive = true;\n\n switch (fieldFilter.op) {\n case Operator.GREATER_THAN_OR_EQUAL:\n case Operator.GREATER_THAN:\n filterValue = valuesGetUpperBound(fieldFilter.value);\n filterInclusive = false;\n break;\n case Operator.EQUAL:\n case Operator.IN:\n case Operator.LESS_THAN_OR_EQUAL:\n filterValue = fieldFilter.value;\n break;\n case Operator.LESS_THAN:\n filterValue = fieldFilter.value;\n filterInclusive = false;\n break;\n case Operator.NOT_EQUAL:\n case Operator.NOT_IN:\n filterValue = MAX_VALUE;\n break;\n default:\n // Remaining filters cannot be used as upper bounds.\n }\n\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: filterValue, inclusive: filterInclusive }\n ) > 0\n ) {\n value = filterValue;\n inclusive = filterInclusive;\n }\n }\n\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (bound !== null) {\n for (let i = 0; i < target.orderBy.length; ++i) {\n const orderBy = target.orderBy[i];\n if (orderBy.field.isEqual(fieldPath)) {\n const cursorValue = bound.position[i];\n if (\n upperBoundCompare(\n { value, inclusive },\n { value: cursorValue, inclusive: bound.inclusive }\n ) > 0\n ) {\n value = cursorValue;\n inclusive = bound.inclusive;\n }\n break;\n }\n }\n }\n\n return { value, inclusive };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\nexport function targetGetSegmentCount(target: Target): number {\n let fields = new SortedSet<FieldPath>(FieldPath.comparator);\n let hasArraySegment = false;\n\n for (const filter of target.filters) {\n for (const subFilter of filter.getFlattenedFilters()) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (subFilter.field.isKeyField()) {\n continue;\n }\n\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n if (\n subFilter.op === Operator.ARRAY_CONTAINS ||\n subFilter.op === Operator.ARRAY_CONTAINS_ANY\n ) {\n hasArraySegment = true;\n } else {\n fields = fields.add(subFilter.field);\n }\n }\n }\n\n for (const orderBy of target.orderBy) {\n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n if (!orderBy.field.isKeyField()) {\n fields = fields.add(orderBy.field);\n }\n }\n\n return fields.size + (hasArraySegment ? 1 : 0);\n}\n\nexport function targetHasLimit(target: Target): boolean {\n return target.limit !== null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { compareDocumentsByField, Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { debugAssert, debugCast, fail } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Bound,\n boundSortsAfterDocument,\n boundSortsBeforeDocument\n} from './bound';\nimport { FieldFilter, Filter } from './filter';\nimport { Direction, OrderBy } from './order_by';\nimport {\n canonifyTarget,\n newTarget,\n stringifyTarget,\n Target,\n targetEquals\n} from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * The Query interface defines all external properties of a query.\n *\n * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy`\n * and `queryToTarget`.\n */\nexport interface Query {\n readonly path: ResourcePath;\n readonly collectionGroup: string | null;\n readonly explicitOrderBy: OrderBy[];\n readonly filters: Filter[];\n readonly limit: number | null;\n readonly limitType: LimitType;\n readonly startAt: Bound | null;\n readonly endAt: Bound | null;\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 *\n * Visible for testing.\n */\nexport class QueryImpl implements Query {\n memoizedNormalizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // non-aggregate queries.\n memoizedTarget: Target | null = null;\n\n // The corresponding `Target` of this `Query` instance, for use with\n // aggregate queries. Unlike targets for non-aggregate queries,\n // aggregate query targets do not contain normalized order-bys, they only\n // contain explicit order-bys.\n memoizedAggregateTarget: 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 debugAssert(\n this.startAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n if (this.endAt) {\n debugAssert(\n this.endAt.position.length <= queryNormalizedOrderBy(this).length,\n 'Bound is longer than orderBy'\n );\n }\n }\n}\n\n/** Creates a new Query instance with the options provided. */\nexport function newQuery(\n path: ResourcePath,\n collectionGroup: string | null,\n explicitOrderBy: OrderBy[],\n filters: Filter[],\n limit: number | null,\n limitType: LimitType,\n startAt: Bound | null,\n endAt: Bound | null\n): Query {\n return new QueryImpl(\n path,\n collectionGroup,\n explicitOrderBy,\n filters,\n limit,\n limitType,\n startAt,\n endAt\n );\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */\nexport function newQueryForPath(path: ResourcePath): Query {\n return new QueryImpl(path);\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 */\nexport function asCollectionQueryAtPath(\n query: Query,\n path: ResourcePath\n): Query {\n return new QueryImpl(\n path,\n /*collectionGroup=*/ null,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nexport function queryMatchesAllDocuments(query: Query): boolean {\n return (\n query.filters.length === 0 &&\n query.limit === null &&\n query.startAt == null &&\n query.endAt == null &&\n (query.explicitOrderBy.length === 0 ||\n (query.explicitOrderBy.length === 1 &&\n query.explicitOrderBy[0].field.isKeyField()))\n );\n}\n\n// Returns the sorted set of inequality filter fields used in this query.\nexport function getInequalityFilterFields(query: Query): SortedSet<FieldPath> {\n let result = new SortedSet<FieldPath>(FieldPath.comparator);\n query.filters.forEach((filter: Filter) => {\n const subFilters = filter.getFlattenedFilters();\n subFilters.forEach((filter: FieldFilter) => {\n if (filter.isInequality()) {\n result = result.add(filter.field);\n }\n });\n });\n return result;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\nexport function newQueryForCollectionGroup(collectionId: string): Query {\n return new QueryImpl(ResourcePath.emptyPath(), collectionId);\n}\n\n/**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\nexport function isDocumentQuery(query: Query): boolean {\n return (\n DocumentKey.isDocumentKey(query.path) &&\n query.collectionGroup === null &&\n query.filters.length === 0\n );\n}\n\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nexport function isCollectionGroupQuery(query: Query): boolean {\n return query.collectionGroup !== null;\n}\n\n/**\n * Returns the normalized order-by constraint that is used to execute the Query,\n * which can be different from the order-by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`). The normalized order-by\n * includes implicit order-bys in addition to the explicit user provided\n * order-bys.\n */\nexport function queryNormalizedOrderBy(query: Query): OrderBy[] {\n const queryImpl = debugCast(query, QueryImpl);\n if (queryImpl.memoizedNormalizedOrderBy === null) {\n queryImpl.memoizedNormalizedOrderBy = [];\n const fieldsNormalized = new Set<string>();\n\n // Any explicit order by fields should be added as is.\n for (const orderBy of queryImpl.explicitOrderBy) {\n queryImpl.memoizedNormalizedOrderBy.push(orderBy);\n fieldsNormalized.add(orderBy.field.canonicalString());\n }\n\n // The order of the implicit ordering always matches the last explicit order by.\n const lastDirection =\n queryImpl.explicitOrderBy.length > 0\n ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n\n // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical\n // order. When there are multiple inequality filters on the same field, the field should be added\n // only once.\n // Note: `SortedSet<FieldPath>` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet<FieldPath> =\n getInequalityFilterFields(queryImpl);\n inequalityFields.forEach(field => {\n if (\n !fieldsNormalized.has(field.canonicalString()) &&\n !field.isKeyField()\n ) {\n queryImpl.memoizedNormalizedOrderBy!.push(\n new OrderBy(field, lastDirection)\n );\n }\n });\n\n // Add the document key field to the last if it is not explicitly ordered.\n if (!fieldsNormalized.has(FieldPath.keyField().canonicalString())) {\n queryImpl.memoizedNormalizedOrderBy.push(\n new OrderBy(FieldPath.keyField(), lastDirection)\n );\n }\n }\n return queryImpl.memoizedNormalizedOrderBy;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation.\n */\nexport function queryToTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n if (!queryImpl.memoizedTarget) {\n queryImpl.memoizedTarget = _queryToTarget(\n queryImpl,\n queryNormalizedOrderBy(query)\n );\n }\n\n return queryImpl.memoizedTarget;\n}\n\n/**\n * Converts this `Query` instance to its corresponding `Target` representation,\n * for use within an aggregate query. Unlike targets for non-aggregate queries,\n * aggregate query targets do not contain normalized order-bys, they only\n * contain explicit order-bys.\n */\nexport function queryToAggregateTarget(query: Query): Target {\n const queryImpl = debugCast(query, QueryImpl);\n\n if (!queryImpl.memoizedAggregateTarget) {\n // Do not include implicit order-bys for aggregate queries.\n queryImpl.memoizedAggregateTarget = _queryToTarget(\n queryImpl,\n query.explicitOrderBy\n );\n }\n\n return queryImpl.memoizedAggregateTarget;\n}\n\nfunction _queryToTarget(queryImpl: QueryImpl, orderBys: OrderBy[]): Target {\n if (queryImpl.limitType === LimitType.First) {\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n queryImpl.startAt,\n queryImpl.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n orderBys = orderBys.map(orderBy => {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n return new OrderBy(orderBy.field, dir);\n });\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = queryImpl.endAt\n ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)\n : null;\n const endAt = queryImpl.startAt\n ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)\n : null;\n\n // Now return as a LimitType.First query.\n return newTarget(\n queryImpl.path,\n queryImpl.collectionGroup,\n orderBys,\n queryImpl.filters,\n queryImpl.limit,\n startAt,\n endAt\n );\n }\n}\n\nexport function queryWithAddedFilter(query: Query, filter: Filter): Query {\n debugAssert(\n !isDocumentQuery(query),\n 'No filtering allowed for document query'\n );\n\n const newFilters = query.filters.concat([filter]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n newFilters,\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query {\n debugAssert(\n !query.startAt && !query.endAt,\n 'Bounds must be set after orderBy'\n );\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = query.explicitOrderBy.concat([orderBy]);\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n newOrderBy,\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithLimit(\n query: Query,\n limit: number | null,\n limitType: LimitType\n): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n limit,\n limitType,\n query.startAt,\n query.endAt\n );\n}\n\nexport function queryWithStartAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n bound,\n query.endAt\n );\n}\n\nexport function queryWithEndAt(query: Query, bound: Bound): Query {\n return new QueryImpl(\n query.path,\n query.collectionGroup,\n query.explicitOrderBy.slice(),\n query.filters.slice(),\n query.limit,\n query.limitType,\n query.startAt,\n bound\n );\n}\n\nexport function queryEquals(left: Query, right: Query): boolean {\n return (\n targetEquals(queryToTarget(left), queryToTarget(right)) &&\n left.limitType === right.limitType\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.\nexport function canonifyQuery(query: Query): string {\n return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;\n}\n\nexport function stringifyQuery(query: Query): string {\n return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${\n query.limitType\n })`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */\nexport function queryMatches(query: Query, doc: Document): boolean {\n return (\n doc.isFoundDocument() &&\n queryMatchesPathAndCollectionGroup(query, doc) &&\n queryMatchesOrderBy(query, doc) &&\n queryMatchesFilters(query, doc) &&\n queryMatchesBounds(query, doc)\n );\n}\n\nfunction queryMatchesPathAndCollectionGroup(\n query: Query,\n doc: Document\n): boolean {\n const docPath = doc.key.path;\n if (query.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(query.collectionGroup) &&\n query.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(query.path)) {\n // exact match for document queries\n return query.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return query.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 */\nfunction queryMatchesOrderBy(query: Query, doc: Document): boolean {\n // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const orderBy of queryNormalizedOrderBy(query)) {\n // order-by key always matches\n if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n}\n\nfunction queryMatchesFilters(query: Query, doc: Document): boolean {\n for (const filter of query.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n}\n\n/** Makes sure a document is within the bounds, if provided. */\nfunction queryMatchesBounds(query: Query, doc: Document): boolean {\n if (\n query.startAt &&\n !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n if (\n query.endAt &&\n !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */\nexport function queryCollectionGroup(query: Query): string {\n return (\n query.collectionGroup ||\n (query.path.length % 2 === 1\n ? query.path.lastSegment()\n : query.path.get(query.path.length - 2))\n );\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */\nexport function newQueryComparator(\n query: Query\n): (d1: Document, d2: Document) => number {\n return (d1: Document, d2: Document): number => {\n let comparedOnKeyField = false;\n for (const orderBy of queryNormalizedOrderBy(query)) {\n const comp = compareDocs(orderBy, 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 debugAssert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n };\n}\n\nexport function compareDocs(\n orderBy: OrderBy,\n d1: Document,\n d2: Document\n): number {\n const comparison = orderBy.field.isKeyField()\n ? DocumentKey.comparator(d1.key, d2.key)\n : compareDocumentsByField(orderBy.field, d1, d2);\n switch (orderBy.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + orderBy.dir);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { forEach, isEmpty } from './obj';\n\ntype Entry<K, V> = [K, V];\n\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nexport class ObjectMap<KeyType, ValueType> {\n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n private inner: {\n [canonicalId: string]: Array<Entry<KeyType, ValueType>>;\n } = {};\n\n /** The number of entries stored in the map */\n private innerSize = 0;\n\n constructor(\n private mapKeyFn: (key: KeyType) => string,\n private equalsFn: (l: KeyType, r: KeyType) => boolean\n ) {}\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 (this.equalsFn(otherKey, 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 this.innerSize++;\n return;\n }\n for (let i = 0; i < matches.length; i++) {\n if (this.equalsFn(matches[i][0], key)) {\n // This is updating an existing entry and does not increase `innerSize`.\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n this.innerSize++;\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 (this.equalsFn(matches[i][0], key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n } else {\n matches.splice(i, 1);\n }\n this.innerSize--;\n return true;\n }\n }\n return false;\n }\n\n forEach(fn: (key: KeyType, val: ValueType) => void): void {\n forEach(this.inner, (_, entries) => {\n for (const [k, v] of entries) {\n fn(k, v);\n }\n });\n }\n\n isEmpty(): boolean {\n return isEmpty(this.inner);\n }\n\n size(): number {\n return this.innerSize;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { OverlayedDocument } from '../local/overlayed_document';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\nimport { Overlay } from './overlay';\n\n/** Miscellaneous collection types / constants. */\n\nexport type MutableDocumentMap = SortedMap<DocumentKey, MutableDocument>;\nconst EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap<DocumentKey, MutableDocument>(\n DocumentKey.comparator\n);\nexport function mutableDocumentMap(): MutableDocumentMap {\n return EMPTY_MUTABLE_DOCUMENT_MAP;\n}\n\nexport interface DocumentSizeEntries {\n documents: MutableDocumentMap;\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(...docs: Document[]): DocumentMap {\n let map = EMPTY_DOCUMENT_MAP;\n for (const doc of docs) {\n map = map.insert(doc.key, doc);\n }\n return map;\n}\n\nexport type OverlayedDocumentMap = DocumentKeyMap<OverlayedDocument>;\nexport function newOverlayedDocumentMap(): OverlayedDocumentMap {\n return newDocumentKeyMap<OverlayedDocument>();\n}\n\nexport function convertOverlayedDocumentMapToDocumentMap(\n collection: OverlayedDocumentMap\n): DocumentMap {\n let documents = EMPTY_DOCUMENT_MAP;\n collection.forEach(\n (k, v) => (documents = documents.insert(k, v.overlayedDocument))\n );\n return documents;\n}\n\nexport type OverlayMap = DocumentKeyMap<Overlay>;\nexport function newOverlayMap(): OverlayMap {\n return newDocumentKeyMap<Overlay>();\n}\n\nexport type MutationMap = DocumentKeyMap<Mutation>;\nexport function newMutationMap(): MutationMap {\n return newDocumentKeyMap<Mutation>();\n}\n\nexport type DocumentKeyMap<T> = ObjectMap<DocumentKey, T>;\nexport function newDocumentKeyMap<T>(): DocumentKeyMap<T> {\n return new ObjectMap<DocumentKey, T>(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { isNegativeZero, isSafeInteger } from '../util/types';\n\n/** Base interface for the Serializer implementation. */\nexport interface Serializer {\n readonly useProto3Json: boolean;\n}\n\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */\nexport function toDouble(serializer: Serializer, value: number): ProtoValue {\n if (serializer.useProto3Json) {\n if (isNaN(value)) {\n return { doubleValue: 'NaN' };\n } else if (value === Infinity) {\n return { doubleValue: 'Infinity' };\n } else if (value === -Infinity) {\n return { doubleValue: '-Infinity' };\n }\n }\n return { doubleValue: isNegativeZero(value) ? '-0' : value };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */\nexport function toInteger(value: number): ProtoValue {\n return { integerValue: '' + value };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */\nexport function toNumber(serializer: Serializer, value: number): ProtoValue {\n return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Serializer, toDouble, toInteger } from '../remote/number_serializer';\nimport { debugAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport { normalizeNumber } from './normalize';\nimport { serverTimestamp } from './server_timestamps';\nimport { isArray, isInteger, isNumber, valueEquals } from './values';\n\n/** Used to represent a field transform on a mutation. */\nexport class TransformOperation {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n private _ = undefined;\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\nexport function applyTransformOperationToLocalView(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n localWriteTime: Timestamp\n): ProtoValue {\n if (transform instanceof ServerTimestampTransform) {\n return serverTimestamp(localWriteTime, previousValue);\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n } else {\n debugAssert(\n transform instanceof NumericIncrementTransformOperation,\n 'Expected NumericIncrementTransformOperation but was: ' + transform\n );\n return applyNumericIncrementTransformOperationToLocalView(\n transform,\n previousValue\n );\n }\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\nexport function applyTransformOperationToRemoteDocument(\n transform: TransformOperation,\n previousValue: ProtoValue | null,\n transformResult: ProtoValue | null\n): ProtoValue {\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 if (transform instanceof ArrayUnionTransformOperation) {\n return applyArrayUnionTransformOperation(transform, previousValue);\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return applyArrayRemoveTransformOperation(transform, previousValue);\n }\n\n debugAssert(\n transformResult !== null,\n \"Didn't receive transformResult for non-array transform\"\n );\n return transformResult;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\nexport function computeTransformOperationBaseValue(\n transform: TransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue | null {\n if (transform instanceof NumericIncrementTransformOperation) {\n return isNumber(previousValue) ? previousValue! : { integerValue: 0 };\n }\n return null;\n}\n\nexport function transformOperationEquals(\n left: TransformOperation,\n right: TransformOperation\n): boolean {\n if (\n left instanceof ArrayUnionTransformOperation &&\n right instanceof ArrayUnionTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof ArrayRemoveTransformOperation &&\n right instanceof ArrayRemoveTransformOperation\n ) {\n return arrayEquals(left.elements, right.elements, valueEquals);\n } else if (\n left instanceof NumericIncrementTransformOperation &&\n right instanceof NumericIncrementTransformOperation\n ) {\n return valueEquals(left.operand, right.operand);\n }\n\n return (\n left instanceof ServerTimestampTransform &&\n right instanceof ServerTimestampTransform\n );\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform extends TransformOperation {}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayUnionTransformOperation(\n transform: ArrayUnionTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n const values = coercedFieldValuesArray(previousValue);\n for (const toUnion of transform.elements) {\n if (!values.some(element => valueEquals(element, toUnion))) {\n values.push(toUnion);\n }\n }\n return { arrayValue: { values } };\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation extends TransformOperation {\n constructor(readonly elements: ProtoValue[]) {\n super();\n }\n}\n\nfunction applyArrayRemoveTransformOperation(\n transform: ArrayRemoveTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n let values = coercedFieldValuesArray(previousValue);\n for (const toRemove of transform.elements) {\n values = values.filter(element => !valueEquals(element, toRemove));\n }\n return { arrayValue: { values } };\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 extends TransformOperation {\n constructor(readonly serializer: Serializer, readonly operand: ProtoValue) {\n super();\n debugAssert(\n isNumber(operand),\n 'NumericIncrementTransform transform requires a NumberValue'\n );\n }\n}\n\nexport function applyNumericIncrementTransformOperationToLocalView(\n transform: NumericIncrementTransformOperation,\n previousValue: ProtoValue | null\n): ProtoValue {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const baseValue = computeTransformOperationBaseValue(\n transform,\n previousValue\n )!;\n const sum = asNumber(baseValue) + asNumber(transform.operand);\n if (isInteger(baseValue) && isInteger(transform.operand)) {\n return toInteger(sum);\n } else {\n return toDouble(transform.serializer, sum);\n }\n}\n\nfunction asNumber(value: ProtoValue): number {\n return normalizeNumber(value.integerValue || value.doubleValue);\n}\n\nfunction coercedFieldValuesArray(value: ProtoValue | null): ProtoValue[] {\n return isArray(value) && value.arrayValue.values\n ? value.arrayValue.values.slice()\n : [];\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { Document, MutableDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './field_mask';\nimport { ObjectValue } from './object_value';\nimport { FieldPath } from './path';\nimport {\n applyTransformOperationToLocalView,\n applyTransformOperationToRemoteDocument,\n computeTransformOperationBaseValue,\n TransformOperation,\n transformOperationEquals\n} from './transform_operation';\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\nexport function fieldTransformEquals(\n left: FieldTransform,\n right: FieldTransform\n): boolean {\n return (\n left.field.isEqual(right.field) &&\n transformOperationEquals(left.transform, right.transform)\n );\n}\n\nexport function fieldTransformsAreEqual(\n left?: FieldTransform[],\n right?: FieldTransform[]\n): boolean {\n if (left === undefined && right === undefined) {\n return true;\n }\n\n if (left && right) {\n return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r));\n }\n\n return false;\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 mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n readonly transformResults: Array<ProtoValue | null>\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\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 private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n debugAssert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new empty Precondition. */\n static none(): Precondition {\n return new Precondition();\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 isEqual(other: Precondition): boolean {\n return (\n this.exists === other.exists &&\n (this.updateTime\n ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)\n : !other.updateTime)\n );\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */\nexport function preconditionIsValidForDocument(\n precondition: Precondition,\n document: MutableDocument\n): boolean {\n if (precondition.updateTime !== undefined) {\n return (\n document.isFoundDocument() &&\n document.version.isEqual(precondition.updateTime)\n );\n } else if (precondition.exists !== undefined) {\n return precondition.exists === document.isFoundDocument();\n } else {\n debugAssert(precondition.isNone, 'Precondition should be empty');\n return true;\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 and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n abstract readonly fieldTransforms: FieldTransform[];\n /**\n * Returns a `FieldMask` representing the fields that will be changed by\n * applying this mutation. Returns `null` if the mutation will overwrite the\n * entire document.\n */\n abstract getFieldMask(): FieldMask | null;\n}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */\nexport function calculateOverlayMutation(\n doc: MutableDocument,\n mask: FieldMask | null\n): Mutation | null {\n if (!doc.hasLocalMutations || (mask && mask!.fields.length === 0)) {\n return null;\n }\n\n // mask is null when sets or deletes are applied to the current document.\n if (mask === null) {\n if (doc.isNoDocument()) {\n return new DeleteMutation(doc.key, Precondition.none());\n } else {\n return new SetMutation(doc.key, doc.data, Precondition.none());\n }\n } else {\n const docValue = doc.data;\n const patchValue = ObjectValue.empty();\n let maskSet = new SortedSet<FieldPath>(FieldPath.comparator);\n for (let path of mask.fields) {\n if (!maskSet.has(path)) {\n let value = docValue.field(path);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n if (value === null && path.length > 1) {\n path = path.popLast();\n value = docValue.field(path);\n }\n if (value === null) {\n patchValue.delete(path);\n } else {\n patchValue.set(path, value);\n }\n maskSet = maskSet.add(path);\n }\n }\n return new PatchMutation(\n doc.key,\n patchValue,\n new FieldMask(maskSet.toArray()),\n Precondition.none()\n );\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */\nexport function mutationApplyToRemoteDocument(\n mutation: Mutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n mutationVerifyKeyMatches(mutation, document);\n if (mutation instanceof SetMutation) {\n setMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else if (mutation instanceof PatchMutation) {\n patchMutationApplyToRemoteDocument(mutation, document, mutationResult);\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n deleteMutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */\nexport function mutationApplyToLocalView(\n mutation: Mutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n mutationVerifyKeyMatches(mutation, document);\n\n if (mutation instanceof SetMutation) {\n return setMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else if (mutation instanceof PatchMutation) {\n return patchMutationApplyToLocalView(\n mutation,\n document,\n previousMask,\n localWriteTime\n );\n } else {\n debugAssert(\n mutation instanceof DeleteMutation,\n 'Unexpected mutation type: ' + mutation\n );\n return deleteMutationApplyToLocalView(mutation, document, previousMask);\n }\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\nexport function mutationExtractBaseValue(\n mutation: Mutation,\n document: Document\n): ObjectValue | null {\n let baseObject: ObjectValue | null = null;\n for (const fieldTransform of mutation.fieldTransforms) {\n const existingValue = document.data.field(fieldTransform.field);\n const coercedValue = computeTransformOperationBaseValue(\n fieldTransform.transform,\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject === null) {\n baseObject = ObjectValue.empty();\n }\n baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n return baseObject ? baseObject : null;\n}\n\nexport function mutationEquals(left: Mutation, right: Mutation): boolean {\n if (left.type !== right.type) {\n return false;\n }\n\n if (!left.key.isEqual(right.key)) {\n return false;\n }\n\n if (!left.precondition.isEqual(right.precondition)) {\n return false;\n }\n\n if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) {\n return false;\n }\n\n if (left.type === MutationType.Set) {\n return (left as SetMutation).value.isEqual((right as SetMutation).value);\n }\n\n if (left.type === MutationType.Patch) {\n return (\n (left as PatchMutation).data.isEqual((right as PatchMutation).data) &&\n (left as PatchMutation).fieldMask.isEqual(\n (right as PatchMutation).fieldMask\n )\n );\n }\n\n return true;\n}\n\nfunction mutationVerifyKeyMatches(\n mutation: Mutation,\n document: MutableDocument\n): void {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply a mutation to a document with the same key'\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 readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction setMutationApplyToRemoteDocument(\n mutation: SetMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const newData = mutation.value.clone();\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction setMutationApplyToLocalView(\n mutation: SetMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return previousMask;\n }\n\n const newData = mutation.value.clone();\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n return null; // SetMutation overwrites all fields.\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 readonly fieldTransforms: FieldTransform[] = []\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n getFieldMask(): FieldMask | null {\n return this.fieldMask;\n }\n}\n\nfunction patchMutationApplyToRemoteDocument(\n mutation: PatchMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n document.convertToUnknownDocument(mutationResult.version);\n return;\n }\n\n const transformResults = serverTransformResults(\n mutation.fieldTransforms,\n document,\n mutationResult.transformResults\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(mutationResult.version, newData)\n .setHasCommittedMutations();\n}\n\nfunction patchMutationApplyToLocalView(\n mutation: PatchMutation,\n document: MutableDocument,\n previousMask: FieldMask | null,\n localWriteTime: Timestamp\n): FieldMask | null {\n if (!preconditionIsValidForDocument(mutation.precondition, document)) {\n return previousMask;\n }\n\n const transformResults = localTransformResults(\n mutation.fieldTransforms,\n localWriteTime,\n document\n );\n const newData = document.data;\n newData.setAll(getPatch(mutation));\n newData.setAll(transformResults);\n document\n .convertToFoundDocument(document.version, newData)\n .setHasLocalMutations();\n\n if (previousMask === null) {\n return null;\n }\n\n return previousMask\n .unionWith(mutation.fieldMask.fields)\n .unionWith(mutation.fieldTransforms.map(transform => transform.field));\n}\n\n/**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */\nfunction getPatch(mutation: PatchMutation): Map<FieldPath, ProtoValue | null> {\n const result = new Map<FieldPath, ProtoValue | null>();\n mutation.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = mutation.data.field(fieldPath);\n result.set(fieldPath, newValue);\n }\n });\n return result;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */\nfunction serverTransformResults(\n fieldTransforms: FieldTransform[],\n mutableDocument: MutableDocument,\n serverTransformResults: Array<ProtoValue | null>\n): Map<FieldPath, ProtoValue> {\n const transformResults = new Map<FieldPath, ProtoValue>();\n hardAssert(\n fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = fieldTransforms[i];\n const transform = fieldTransform.transform;\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToRemoteDocument(\n transform,\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 * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */\nfunction localTransformResults(\n fieldTransforms: FieldTransform[],\n localWriteTime: Timestamp,\n mutableDocument: MutableDocument\n): Map<FieldPath, ProtoValue> {\n const transformResults = new Map<FieldPath, ProtoValue>();\n for (const fieldTransform of fieldTransforms) {\n const transform = fieldTransform.transform;\n\n const previousValue = mutableDocument.data.field(fieldTransform.field);\n transformResults.set(\n fieldTransform.field,\n applyTransformOperationToLocalView(\n transform,\n previousValue,\n localWriteTime\n )\n );\n }\n return transformResults;\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 readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n\nfunction deleteMutationApplyToRemoteDocument(\n mutation: DeleteMutation,\n document: MutableDocument,\n mutationResult: MutationResult\n): void {\n debugAssert(\n mutationResult.transformResults.length === 0,\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 document\n .convertToNoDocument(mutationResult.version)\n .setHasCommittedMutations();\n}\n\nfunction deleteMutationApplyToLocalView(\n mutation: DeleteMutation,\n document: MutableDocument,\n previousMask: FieldMask | null\n): FieldMask | null {\n debugAssert(\n document.key.isEqual(mutation.key),\n 'Can only apply mutation to document with same key'\n );\n if (preconditionIsValidForDocument(mutation.precondition, document)) {\n document.convertToNoDocument(document.version).setHasLocalMutations();\n return null;\n }\n return previousMask;\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 readonly fieldTransforms: FieldTransform[] = [];\n\n getFieldMask(): FieldMask | null {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { arrayEquals } from '../util/misc';\n\nimport {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n DocumentVersionMap,\n documentVersionMap,\n newMutationMap,\n OverlayedDocumentMap\n} from './collections';\nimport { MutableDocument } from './document';\nimport { FieldMask } from './field_mask';\nimport {\n calculateOverlayMutation,\n Mutation,\n mutationApplyToLocalView,\n mutationApplyToRemoteDocument,\n mutationEquals,\n MutationResult\n} from './mutation';\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 debugAssert(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 compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */\n applyToRemoteDocument(\n document: MutableDocument,\n batchResult: MutationBatchResult\n ): void {\n const mutationResults = batchResult.mutationResults;\n debugAssert(\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(document.key)) {\n const mutationResult = mutationResults[i];\n mutationApplyToRemoteDocument(mutation, document, mutationResult);\n }\n }\n }\n\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */\n applyToLocalView(\n document: MutableDocument,\n mutatedFields: FieldMask | null\n ): FieldMask | null {\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(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n\n // Second, apply all user-provided mutations.\n for (const mutation of this.mutations) {\n if (mutation.key.isEqual(document.key)) {\n mutatedFields = mutationApplyToLocalView(\n mutation,\n document,\n mutatedFields,\n this.localWriteTime\n );\n }\n }\n return mutatedFields;\n }\n\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */\n applyToLocalDocumentSet(\n documentMap: OverlayedDocumentMap,\n documentsWithoutRemoteVersion: DocumentKeySet\n ): MutationMap {\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 const overlays = newMutationMap();\n this.mutations.forEach(m => {\n const overlayedDocument = documentMap.get(m.key)!;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n const mutableDocument =\n overlayedDocument.overlayedDocument as MutableDocument;\n let mutatedFields = this.applyToLocalView(\n mutableDocument,\n overlayedDocument.mutatedFields\n );\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n mutatedFields = documentsWithoutRemoteVersion.has(m.key)\n ? null\n : mutatedFields;\n const overlay = calculateOverlayMutation(mutableDocument, mutatedFields);\n if (overlay !== null) {\n overlays.set(m.key, overlay);\n }\n\n if (!mutableDocument.isValidDocument()) {\n mutableDocument.convertToNoDocument(SnapshotVersion.min());\n }\n });\n return overlays;\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 arrayEquals(this.mutations, other.mutations, (l, r) =>\n mutationEquals(l, r)\n ) &&\n arrayEquals(this.baseMutations, other.baseMutations, (l, r) =>\n mutationEquals(l, r)\n )\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 /**\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=&gt;version mapping (docVersions).\n */\n static from(\n batch: MutationBatch,\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ): MutationBatchResult {\n hardAssert(\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(batch, commitVersion, results, versionMap);\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from './document_key';\nimport { Mutation } from './mutation';\n\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */\nexport class Overlay {\n constructor(readonly largestBatchId: number, readonly mutation: Mutation) {}\n\n getKey(): DocumentKey {\n return this.mutation.key;\n }\n\n isEqual(other: Overlay | null): boolean {\n return other !== null && this.mutation === other.mutation;\n }\n\n toString(): string {\n return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BloomFilter as ProtoBloomFilter } from '../protos/firestore_proto_api';\n\nexport class ExistenceFilter {\n constructor(public count: number, public unchangedNames?: ProtoBloomFilter) {}\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\nexport function newTextEncoder(): TextEncoder {\n return new TextEncoder();\n}\n\n/**\n * An instance of the Platform's 'TextDecoder' implementation.\n */\nexport function newTextDecoder(): TextDecoder {\n return new TextDecoder('utf-8');\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Md5, Integer } from '@firebase/webchannel-wrapper';\n\nimport { newTextEncoder } from '../platform/text_serializer';\n\nconst MAX_64_BIT_UNSIGNED_INTEGER = new Integer([0xffffffff, 0xffffffff], 0);\n\n// Hash a string using md5 hashing algorithm.\nfunction getMd5HashValue(value: string): Uint8Array {\n const encodedValue = newTextEncoder().encode(value);\n const md5 = new Md5();\n md5.update(encodedValue);\n return new Uint8Array(md5.digest());\n}\n\n// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using\n// 2s complement using little endian.\nfunction get64BitUints(Bytes: Uint8Array): [Integer, Integer] {\n const dataView = new DataView(Bytes.buffer);\n const chunk1 = dataView.getUint32(0, /* littleEndian= */ true);\n const chunk2 = dataView.getUint32(4, /* littleEndian= */ true);\n const chunk3 = dataView.getUint32(8, /* littleEndian= */ true);\n const chunk4 = dataView.getUint32(12, /* littleEndian= */ true);\n const integer1 = new Integer([chunk1, chunk2], 0);\n const integer2 = new Integer([chunk3, chunk4], 0);\n return [integer1, integer2];\n}\n\nexport class BloomFilter {\n readonly bitCount: number;\n private readonly bitCountInInteger: Integer;\n\n constructor(\n readonly bitmap: Uint8Array,\n readonly padding: number,\n readonly hashCount: number\n ) {\n if (padding < 0 || padding >= 8) {\n throw new BloomFilterError(`Invalid padding: ${padding}`);\n }\n\n if (hashCount < 0) {\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length > 0 && this.hashCount === 0) {\n // Only empty bloom filter can have 0 hash count.\n throw new BloomFilterError(`Invalid hash count: ${hashCount}`);\n }\n\n if (bitmap.length === 0 && padding !== 0) {\n // Empty bloom filter should have 0 padding.\n throw new BloomFilterError(\n `Invalid padding when bitmap length is 0: ${padding}`\n );\n }\n\n this.bitCount = bitmap.length * 8 - padding;\n // Set the bit count in Integer to avoid repetition in mightContain().\n this.bitCountInInteger = Integer.fromNumber(this.bitCount);\n }\n\n // Calculate the ith hash value based on the hashed 64bit integers,\n // and calculate its corresponding bit index in the bitmap to be checked.\n private getBitIndex(num1: Integer, num2: Integer, hashIndex: number): number {\n // Calculate hashed value h(i) = h1 + (i * h2).\n let hashValue = num1.add(num2.multiply(Integer.fromNumber(hashIndex)));\n // Wrap if hash value overflow 64bit.\n if (hashValue.compare(MAX_64_BIT_UNSIGNED_INTEGER) === 1) {\n hashValue = new Integer([hashValue.getBits(0), hashValue.getBits(1)], 0);\n }\n return hashValue.modulo(this.bitCountInInteger).toNumber();\n }\n\n // Return whether the bit on the given index in the bitmap is set to 1.\n private isBitSet(index: number): boolean {\n // To retrieve bit n, calculate: (bitmap[n / 8] & (0x01 << (n % 8))).\n const byte = this.bitmap[Math.floor(index / 8)];\n const offset = index % 8;\n return (byte & (0x01 << offset)) !== 0;\n }\n\n mightContain(value: string): boolean {\n // Empty bitmap should always return false on membership check.\n if (this.bitCount === 0) {\n return false;\n }\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n if (!this.isBitSet(index)) {\n return false;\n }\n }\n return true;\n }\n\n /** Create bloom filter for testing purposes only. */\n static create(\n bitCount: number,\n hashCount: number,\n contains: string[]\n ): BloomFilter {\n const padding = bitCount % 8 === 0 ? 0 : 8 - (bitCount % 8);\n const bitmap = new Uint8Array(Math.ceil(bitCount / 8));\n const bloomFilter = new BloomFilter(bitmap, padding, hashCount);\n contains.forEach(item => bloomFilter.insert(item));\n return bloomFilter;\n }\n\n private insert(value: string): void {\n if (this.bitCount === 0) {\n return;\n }\n\n const md5HashedValue = getMd5HashValue(value);\n const [hash1, hash2] = get64BitUints(md5HashedValue);\n for (let i = 0; i < this.hashCount; i++) {\n const index = this.getBitIndex(hash1, hash2, i);\n this.setBit(index);\n }\n }\n\n private setBit(index: number): void {\n const indexOfByte = Math.floor(index / 8);\n const offset = index % 8;\n this.bitmap[indexOfByte] |= 0x01 << offset;\n }\n}\n\nexport class BloomFilterError extends Error {\n readonly name = 'BloomFilterError';\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap,\n MutableDocumentMap\n} from '../model/collections';\nimport { ByteString } from '../util/byte_string';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\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: Map<TargetId, TargetChange>,\n /**\n * A map of targets that is known to be inconsistent, and the purpose for\n * re-listening. Listens for these targets should be re-established without\n * resume tokens.\n */\n readonly targetMismatches: SortedMap<TargetId, TargetPurpose>,\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: MutableDocumentMap,\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 resumeToken: ByteString\n ): RemoteEvent {\n const targetChanges = new Map<TargetId, TargetChange>();\n targetChanges.set(\n targetId,\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current,\n resumeToken\n )\n );\n return new RemoteEvent(\n SnapshotVersion.min(),\n targetChanges,\n new SortedMap<TargetId, TargetPurpose>(primitiveComparator),\n mutableDocumentMap(),\n documentKeySet()\n );\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */\nexport class TargetChange {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n readonly resumeToken: ByteString,\n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n readonly current: boolean,\n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n readonly addedDocuments: DocumentKeySet,\n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n readonly modifiedDocuments: DocumentKeySet,\n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n readonly removedDocuments: DocumentKeySet\n ) {}\n\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */\n static createSynthesizedTargetChangeForCurrentChange(\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n ): TargetChange {\n return new TargetChange(\n resumeToken,\n current,\n documentKeySet(),\n documentKeySet(),\n documentKeySet()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseId } from '../core/database_info';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { ChangeType } from '../core/view_snapshot';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n mutableDocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { normalizeByteString } from '../model/normalize';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { Base64DecodeError } from '../util/base64_decode_error';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport {\n testingHooksSpi,\n ExistenceFilterMismatchInfo as TestingHooksExistenceFilterMismatchInfo\n} from '../util/testing_hooks_spi';\n\nimport { BloomFilter, BloomFilterError } from './bloom_filter';\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: MutableDocument | null\n ) {}\n}\n\nexport class ExistenceFilterChange {\n constructor(\n public targetId: TargetId,\n public existenceFilter: ExistenceFilter\n ) {}\n}\n\nexport const enum WatchTargetChangeState {\n NoChange,\n Added,\n Removed,\n Current,\n Reset\n}\n\nconst enum BloomFilterApplicationStatus {\n Success,\n Skipped,\n FalsePositive\n}\nexport class WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n public state: WatchTargetChangeState,\n /** The target IDs that were added/removed/set. */\n public targetIds: TargetId[],\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n public resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /** An RPC error indicating why the watch failed. */\n public cause: FirestoreError | null = null\n ) {}\n}\n\n/** Tracks the internal state of a Watch target. */\nclass TargetState {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n private pendingResponses = 0;\n\n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n private documentChanges: SortedMap<DocumentKey, ChangeType> =\n snapshotChangesMap();\n\n /** See public getters for explanations of these fields. */\n private _resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n private _current = false;\n\n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n private _hasPendingChanges = true;\n\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */\n get current(): boolean {\n return this._current;\n }\n\n /** The last resume token sent to us for this target. */\n get resumeToken(): ByteString {\n return this._resumeToken;\n }\n\n /** Whether this target has pending target adds or target removes. */\n get isPending(): boolean {\n return this.pendingResponses !== 0;\n }\n\n /** Whether we have modified any state that should trigger a snapshot. */\n get hasPendingChanges(): boolean {\n return this._hasPendingChanges;\n }\n\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */\n updateResumeToken(resumeToken: ByteString): void {\n if (resumeToken.approximateByteSize() > 0) {\n this._hasPendingChanges = true;\n this._resumeToken = resumeToken;\n }\n }\n\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */\n toTargetChange(): TargetChange {\n let addedDocuments = documentKeySet();\n let modifiedDocuments = documentKeySet();\n let removedDocuments = documentKeySet();\n\n this.documentChanges.forEach((key, changeType) => {\n switch (changeType) {\n case ChangeType.Added:\n addedDocuments = addedDocuments.add(key);\n break;\n case ChangeType.Modified:\n modifiedDocuments = modifiedDocuments.add(key);\n break;\n case ChangeType.Removed:\n removedDocuments = removedDocuments.add(key);\n break;\n default:\n fail('Encountered invalid change type: ' + changeType);\n }\n });\n\n return new TargetChange(\n this._resumeToken,\n this._current,\n addedDocuments,\n modifiedDocuments,\n removedDocuments\n );\n }\n\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */\n clearPendingChanges(): void {\n this._hasPendingChanges = false;\n this.documentChanges = snapshotChangesMap();\n }\n\n addDocumentChange(key: DocumentKey, changeType: ChangeType): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.insert(key, changeType);\n }\n\n removeDocumentChange(key: DocumentKey): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.remove(key);\n }\n\n recordPendingTargetRequest(): void {\n this.pendingResponses += 1;\n }\n\n recordTargetResponse(): void {\n this.pendingResponses -= 1;\n hardAssert(\n this.pendingResponses >= 0,\n '`pendingResponses` is less than 0. Actual value: ' +\n this.pendingResponses +\n '. This indicates that the SDK received more target acks from the ' +\n 'server than expected. The SDK should not continue to operate.'\n );\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 /**\n * Returns the database ID of the Firestore instance.\n */\n getDatabaseId(): DatabaseId;\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 = new Map<TargetId, TargetState>();\n\n /** Keeps track of the documents to update since the last raised snapshot. */\n private pendingDocumentUpdates = mutableDocumentMap();\n\n /** A mapping of document keys to their set of target IDs. */\n private pendingDocumentTargetMapping = documentTargetMap();\n\n /**\n * A map 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 SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n );\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 && docChange.newDoc.isFoundDocument()) {\n this.addDocumentToTarget(targetId, docChange.newDoc);\n } else {\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 debugAssert(\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 this.targetStates.forEach((_, targetId) => {\n if (this.isActiveTarget(targetId)) {\n fn(targetId);\n }\n });\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 (targetIsDocumentTarget(target)) {\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 MutableDocument.newNoDocument(key, SnapshotVersion.min())\n );\n } else {\n hardAssert(\n expectedCount === 1,\n 'Single document existence filter with count: ' + expectedCount\n );\n }\n } else {\n const currentSize = this.getCurrentDocumentCountForTarget(targetId);\n // Existence filter mismatch. Mark the documents as being in limbo, and\n // raise a snapshot with `isFromCache:true`.\n if (currentSize !== expectedCount) {\n // Apply bloom filter to identify and mark removed documents.\n const bloomFilter = this.parseBloomFilter(watchChange);\n const status = bloomFilter\n ? this.applyBloomFilter(bloomFilter, watchChange, currentSize)\n : BloomFilterApplicationStatus.Skipped;\n\n if (status !== BloomFilterApplicationStatus.Success) {\n // If bloom filter application fails, we reset the mapping and\n // trigger re-run of the query.\n this.resetTarget(targetId);\n\n const purpose: TargetPurpose =\n status === BloomFilterApplicationStatus.FalsePositive\n ? TargetPurpose.ExistenceFilterMismatchBloom\n : TargetPurpose.ExistenceFilterMismatch;\n this.pendingTargetResets = this.pendingTargetResets.insert(\n targetId,\n purpose\n );\n }\n testingHooksSpi?.notifyOnExistenceFilterMismatch(\n createExistenceFilterMismatchInfoForTestingHooks(\n currentSize,\n watchChange.existenceFilter,\n this.metadataProvider.getDatabaseId(),\n bloomFilter,\n status\n )\n );\n }\n }\n }\n }\n\n /**\n * Parse the bloom filter from the \"unchanged_names\" field of an existence\n * filter.\n */\n private parseBloomFilter(\n watchChange: ExistenceFilterChange\n ): BloomFilter | null {\n const unchangedNames = watchChange.existenceFilter.unchangedNames;\n if (!unchangedNames || !unchangedNames.bits) {\n return null;\n }\n\n const {\n bits: { bitmap = '', padding = 0 },\n hashCount = 0\n } = unchangedNames;\n\n let normalizedBitmap: Uint8Array;\n try {\n normalizedBitmap = normalizeByteString(bitmap).toUint8Array();\n } catch (err) {\n if (err instanceof Base64DecodeError) {\n logWarn(\n 'Decoding the base64 bloom filter in existence filter failed (' +\n err.message +\n '); ignoring the bloom filter and falling back to full re-query.'\n );\n return null;\n } else {\n throw err;\n }\n }\n\n let bloomFilter: BloomFilter;\n try {\n // BloomFilter throws error if the inputs are invalid.\n bloomFilter = new BloomFilter(normalizedBitmap, padding, hashCount);\n } catch (err) {\n if (err instanceof BloomFilterError) {\n logWarn('BloomFilter error: ', err);\n } else {\n logWarn('Applying bloom filter failed: ', err);\n }\n return null;\n }\n\n if (bloomFilter.bitCount === 0) {\n return null;\n }\n\n return bloomFilter;\n }\n\n /**\n * Apply bloom filter to remove the deleted documents, and return the\n * application status.\n */\n private applyBloomFilter(\n bloomFilter: BloomFilter,\n watchChange: ExistenceFilterChange,\n currentCount: number\n ): BloomFilterApplicationStatus {\n const expectedCount = watchChange.existenceFilter.count;\n\n const removedDocumentCount = this.filterRemovedDocuments(\n bloomFilter,\n watchChange.targetId\n );\n\n return expectedCount === currentCount - removedDocumentCount\n ? BloomFilterApplicationStatus.Success\n : BloomFilterApplicationStatus.FalsePositive;\n }\n\n /**\n * Filter out removed documents based on bloom filter membership result and\n * return number of documents removed.\n */\n private filterRemovedDocuments(\n bloomFilter: BloomFilter,\n targetId: number\n ): number {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n let removalCount = 0;\n\n existingKeys.forEach(key => {\n const databaseId = this.metadataProvider.getDatabaseId();\n const documentPath =\n `projects/${databaseId.projectId}` +\n `/databases/${databaseId.database}` +\n `/documents/${key.path.canonicalString()}`;\n\n if (!bloomFilter.mightContain(documentPath)) {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n removalCount++;\n }\n });\n\n return removalCount;\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 = new Map<TargetId, TargetChange>();\n\n this.targetStates.forEach((targetState, targetId) => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n if (targetState.current && targetIsDocumentTarget(targetData.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n //\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 MutableDocument.newNoDocument(key, snapshotVersion)\n );\n }\n }\n\n if (targetState.hasPendingChanges) {\n targetChanges.set(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 this.pendingDocumentUpdates.forEach((_, doc) =>\n doc.setReadTime(snapshotVersion)\n );\n\n const remoteEvent = new RemoteEvent(\n snapshotVersion,\n targetChanges,\n this.pendingTargetResets,\n this.pendingDocumentUpdates,\n resolvedLimboDocuments\n );\n\n this.pendingDocumentUpdates = mutableDocumentMap();\n this.pendingDocumentTargetMapping = documentTargetMap();\n this.pendingTargetResets = new SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n );\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: MutableDocument): 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 =\n 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: MutableDocument | 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 =\n 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 this.targetStates.delete(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 let result = this.targetStates.get(targetId);\n if (!result) {\n result = new TargetState();\n this.targetStates.set(targetId, result);\n }\n return result;\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 =\n this.pendingDocumentTargetMapping.insert(key, targetMapping);\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 logDebug(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.get(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 debugAssert(\n !this.targetStates.get(targetId)!.isPending,\n 'Should only reset active targets'\n );\n this.targetStates.set(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\nfunction createExistenceFilterMismatchInfoForTestingHooks(\n localCacheCount: number,\n existenceFilter: ExistenceFilter,\n databaseId: DatabaseId,\n bloomFilter: BloomFilter | null,\n bloomFilterStatus: BloomFilterApplicationStatus\n): TestingHooksExistenceFilterMismatchInfo {\n const result: TestingHooksExistenceFilterMismatchInfo = {\n localCacheCount,\n existenceFilterCount: existenceFilter.count,\n databaseId: databaseId.database,\n projectId: databaseId.projectId\n };\n\n const unchangedNames = existenceFilter.unchangedNames;\n if (unchangedNames) {\n result.bloomFilter = {\n applied: bloomFilterStatus === BloomFilterApplicationStatus.Success,\n hashCount: unchangedNames?.hashCount ?? 0,\n bitmapLength: unchangedNames?.bits?.bitmap?.length ?? 0,\n padding: unchangedNames?.bits?.padding ?? 0,\n mightContain: (value: string): boolean =>\n bloomFilter?.mightContain(value) ?? false\n };\n }\n\n return result;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Aggregate } from '../core/aggregate';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n compositeFilterIsFlatConjunction,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { targetIsDocumentTarget, Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n DeleteMutation,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { normalizeTimestamp } from '../model/normalize';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { isNanValue, isNullValue } from '../model/values';\nimport {\n ApiClientObjectMap as ProtoApiClientObjectMap,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n CompositeFilterOp as ProtoCompositeFilterOp,\n Cursor as ProtoCursor,\n Document as ProtoDocument,\n DocumentMask as ProtoDocumentMask,\n DocumentsTarget as ProtoDocumentsTarget,\n FieldFilterOp as ProtoFieldFilterOp,\n FieldReference as ProtoFieldReference,\n FieldTransform as ProtoFieldTransform,\n Filter as ProtoFilter,\n ListenResponse as ProtoListenResponse,\n Order as ProtoOrder,\n OrderDirection as ProtoOrderDirection,\n Precondition as ProtoPrecondition,\n QueryTarget as ProtoQueryTarget,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n Aggregation as ProtoAggregation,\n Status as ProtoStatus,\n Target as ProtoTarget,\n TargetChangeTargetChangeType as ProtoTargetChangeTargetChangeType,\n Timestamp as ProtoTimestamp,\n Write as ProtoWrite,\n WriteResult as ProtoWriteResult\n} from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExistenceFilter } from './existence_filter';\nimport { Serializer } from './number_serializer';\nimport { mapCodeFromRpcCode } 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]: ProtoOrderDirection } = {};\n dirs[Direction.ASCENDING] = 'ASCENDING';\n dirs[Direction.DESCENDING] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: ProtoFieldFilterOp } = {};\n ops[Operator.LESS_THAN] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL] = 'EQUAL';\n ops[Operator.NOT_EQUAL] = 'NOT_EQUAL';\n ops[Operator.ARRAY_CONTAINS] = 'ARRAY_CONTAINS';\n ops[Operator.IN] = 'IN';\n ops[Operator.NOT_IN] = 'NOT_IN';\n ops[Operator.ARRAY_CONTAINS_ANY] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\nconst COMPOSITE_OPERATORS = (() => {\n const ops: { [op: string]: ProtoCompositeFilterOp } = {};\n ops[CompositeOperator.AND] = 'AND';\n ops[CompositeOperator.OR] = 'OR';\n return ops;\n})();\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n debugAssert(!isNullOrUndefined(value), description + ' is missing');\n}\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer implements Serializer {\n constructor(\n readonly databaseId: DatabaseId,\n readonly useProto3Json: boolean\n ) {}\n}\n\nfunction fromRpcStatus(status: ProtoStatus): FirestoreError {\n const code =\n status.code === undefined ? Code.UNKNOWN : 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 */\nfunction toInt32Proto(\n serializer: JsonProtoSerializer,\n val: number | null\n): number | { value: number } | null {\n if (serializer.useProto3Json || isNullOrUndefined(val)) {\n return val;\n } else {\n return { value: val };\n }\n}\n\n/**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */\nfunction fromInt32Proto(\n val: number | { value: number } | undefined\n): number | null {\n let result;\n if (typeof val === 'object') {\n result = val.value;\n } else {\n result = val;\n }\n return isNullOrUndefined(result) ? null : result;\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nexport function toTimestamp(\n serializer: JsonProtoSerializer,\n timestamp: Timestamp\n): ProtoTimestamp {\n if (serializer.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\nfunction fromTimestamp(date: ProtoTimestamp): Timestamp {\n const timestamp = normalizeTimestamp(date);\n return new Timestamp(timestamp.seconds, timestamp.nanos);\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nexport function toBytes(\n serializer: JsonProtoSerializer,\n bytes: ByteString\n): string | Uint8Array {\n if (serializer.useProto3Json) {\n return bytes.toBase64();\n } else {\n return bytes.toUint8Array();\n }\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */\nexport function fromBytes(\n serializer: JsonProtoSerializer,\n value: string | Uint8Array | undefined\n): ByteString {\n if (serializer.useProto3Json) {\n hardAssert(\n value === undefined || typeof value === 'string',\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n hardAssert(\n value === undefined || value instanceof Uint8Array,\n 'value must be undefined or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n}\n\nexport function toVersion(\n serializer: JsonProtoSerializer,\n version: SnapshotVersion\n): ProtoTimestamp {\n return toTimestamp(serializer, version.toTimestamp());\n}\n\nexport function fromVersion(version: ProtoTimestamp): SnapshotVersion {\n hardAssert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(fromTimestamp(version));\n}\n\nexport function toResourceName(\n databaseId: DatabaseId,\n path: ResourcePath\n): string {\n return toResourcePath(databaseId, path).canonicalString();\n}\n\nexport function toResourcePath(\n databaseId: DatabaseId,\n path?: ResourcePath\n): ResourcePath {\n const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents');\n return path === undefined ? resourcePath : resourcePath.child(path);\n}\n\nfunction fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n}\n\nexport function toName(\n serializer: JsonProtoSerializer,\n key: DocumentKey\n): string {\n return toResourceName(serializer.databaseId, key.path);\n}\n\nexport function fromName(\n serializer: JsonProtoSerializer,\n name: string\n): DocumentKey {\n const resource = fromResourceName(name);\n\n if (resource.get(1) !== serializer.databaseId.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n serializer.databaseId.projectId\n );\n }\n\n if (resource.get(3) !== serializer.databaseId.database) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n serializer.databaseId.database\n );\n }\n return new DocumentKey(extractLocalPathFromResourceName(resource));\n}\n\nfunction toQueryPath(\n serializer: JsonProtoSerializer,\n path: ResourcePath\n): string {\n return toResourceName(serializer.databaseId, path);\n}\n\nfunction fromQueryPath(name: string): ResourcePath {\n const resourceName = 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.emptyPath();\n }\n return extractLocalPathFromResourceName(resourceName);\n}\n\nexport function getEncodedDatabaseId(serializer: JsonProtoSerializer): string {\n const path = new ResourcePath([\n 'projects',\n serializer.databaseId.projectId,\n 'databases',\n serializer.databaseId.database\n ]);\n return path.canonicalString();\n}\n\nfunction fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n}\n\nfunction extractLocalPathFromResourceName(\n resourceName: ResourcePath\n): ResourcePath {\n hardAssert(\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/** Creates a Document proto from key and fields (but no create/update time) */\nexport function toMutationDocument(\n serializer: JsonProtoSerializer,\n key: DocumentKey,\n fields: ObjectValue\n): ProtoDocument {\n return {\n name: toName(serializer, key),\n fields: fields.value.mapValue.fields\n };\n}\n\nexport function toDocument(\n serializer: JsonProtoSerializer,\n document: MutableDocument\n): ProtoDocument {\n debugAssert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: toName(serializer, document.key),\n fields: document.data.value.mapValue.fields,\n updateTime: toTimestamp(serializer, document.version.toTimestamp()),\n createTime: toTimestamp(serializer, document.createTime.toTimestamp())\n };\n}\n\nexport function fromDocument(\n serializer: JsonProtoSerializer,\n document: ProtoDocument,\n hasCommittedMutations?: boolean\n): MutableDocument {\n const key = fromName(serializer, document.name!);\n const version = fromVersion(document.updateTime!);\n // If we read a document from persistence that is missing createTime, it's due\n // to older SDK versions not storing this information. In such cases, we'll\n // set the createTime to zero. This can be removed in the long term.\n const createTime = document.createTime\n ? fromVersion(document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: document.fields } });\n const result = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\n );\n if (hasCommittedMutations) {\n result.setHasCommittedMutations();\n }\n return hasCommittedMutations ? result.setHasCommittedMutations() : result;\n}\n\nfunction fromFound(\n serializer: JsonProtoSerializer,\n doc: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\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 = fromName(serializer, doc.found.name);\n const version = fromVersion(doc.found.updateTime);\n const createTime = doc.found.createTime\n ? fromVersion(doc.found.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });\n return MutableDocument.newFoundDocument(key, version, createTime, data);\n}\n\nfunction fromMissing(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n hardAssert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = fromName(serializer, result.missing);\n const version = fromVersion(result.readTime);\n return MutableDocument.newNoDocument(key, version);\n}\n\nexport function fromBatchGetDocumentsResponse(\n serializer: JsonProtoSerializer,\n result: ProtoBatchGetDocumentsResponse\n): MutableDocument {\n if ('found' in result) {\n return fromFound(serializer, result);\n } else if ('missing' in result) {\n return fromMissing(serializer, result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n}\n\nexport function fromWatchChange(\n serializer: JsonProtoSerializer,\n change: ProtoListenResponse\n): 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 = fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = fromBytes(serializer, change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && 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 = fromName(serializer, entityChange.document.name);\n const version = fromVersion(entityChange.document.updateTime);\n const createTime = entityChange.document.createTime\n ? fromVersion(entityChange.document.createTime)\n : SnapshotVersion.min();\n const data = new ObjectValue({\n mapValue: { fields: entityChange.document.fields }\n });\n const doc = MutableDocument.newFoundDocument(\n key,\n version,\n createTime,\n data\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 = fromName(serializer, docDelete.document);\n const version = docDelete.readTime\n ? fromVersion(docDelete.readTime)\n : SnapshotVersion.min();\n const doc = MutableDocument.newNoDocument(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 = fromName(serializer, 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 = 0, unchangedNames } = filter;\n const existenceFilter = new ExistenceFilter(count, unchangedNames);\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\nfunction fromWatchTargetChangeState(\n state: ProtoTargetChangeTargetChangeType\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\nexport function versionFromListenResponse(\n change: ProtoListenResponse\n): 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 fromVersion(targetChange.readTime);\n}\n\nexport function toMutation(\n serializer: JsonProtoSerializer,\n mutation: Mutation\n): ProtoWrite {\n let result: ProtoWrite;\n if (mutation instanceof SetMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: toName(serializer, mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: toMutationDocument(serializer, mutation.key, mutation.data),\n updateMask: toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: toName(serializer, mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (mutation.fieldTransforms.length > 0) {\n result.updateTransforms = mutation.fieldTransforms.map(transform =>\n toFieldTransform(serializer, transform)\n );\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = toPrecondition(serializer, mutation.precondition);\n }\n\n return result;\n}\n\nexport function fromMutation(\n serializer: JsonProtoSerializer,\n proto: ProtoWrite\n): Mutation {\n const precondition = proto.currentDocument\n ? fromPrecondition(proto.currentDocument)\n : Precondition.none();\n\n const fieldTransforms = proto.updateTransforms\n ? proto.updateTransforms.map(transform =>\n fromFieldTransform(serializer, transform)\n )\n : [];\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = fromName(serializer, proto.update.name);\n const value = new ObjectValue({\n mapValue: { fields: proto.update.fields }\n });\n\n if (proto.updateMask) {\n const fieldMask = fromDocumentMask(proto.updateMask);\n return new PatchMutation(\n key,\n value,\n fieldMask,\n precondition,\n fieldTransforms\n );\n } else {\n return new SetMutation(key, value, precondition, fieldTransforms);\n }\n } else if (proto.delete) {\n const key = fromName(serializer, proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.verify) {\n const key = fromName(serializer, proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n}\n\nfunction toPrecondition(\n serializer: JsonProtoSerializer,\n precondition: Precondition\n): ProtoPrecondition {\n debugAssert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: toVersion(serializer, precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n}\n\nfunction fromPrecondition(precondition: ProtoPrecondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.none();\n }\n}\n\nfunction fromWriteResult(\n proto: ProtoWriteResult,\n commitTime: ProtoTimestamp\n): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? fromVersion(proto.updateTime)\n : 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 = fromVersion(commitTime);\n }\n\n return new MutationResult(version, proto.transformResults || []);\n}\n\nexport function fromWriteResults(\n protos: ProtoWriteResult[] | undefined,\n commitTime?: ProtoTimestamp\n): MutationResult[] {\n if (protos && protos.length > 0) {\n hardAssert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n}\n\nfunction toFieldTransform(\n serializer: JsonProtoSerializer,\n fieldTransform: FieldTransform\n): ProtoFieldTransform {\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\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: transform.operand\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n}\n\nfunction fromFieldTransform(\n serializer: JsonProtoSerializer,\n proto: ProtoFieldTransform\n): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n hardAssert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = new ServerTimestampTransform();\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(values);\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(values);\n } else if ('increment' in proto) {\n transform = new NumericIncrementTransformOperation(\n serializer,\n proto.increment!\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\nexport function toDocumentsTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): ProtoDocumentsTarget {\n return { documents: [toQueryPath(serializer, target.path)] };\n}\n\nexport function fromDocumentsTarget(\n documentsTarget: ProtoDocumentsTarget\n): Target {\n const count = documentsTarget.documents!.length;\n hardAssert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return queryToTarget(newQueryForPath(fromQueryPath(name)));\n}\n\nexport function toQueryTarget(\n serializer: JsonProtoSerializer,\n target: Target\n): { queryTarget: ProtoQueryTarget; parent: ResourcePath } {\n // Dissect the path into parent, collectionId, and optional key filter.\n const queryTarget: ProtoQueryTarget = { structuredQuery: {} };\n const path = target.path;\n let parent: ResourcePath;\n if (target.collectionGroup !== null) {\n debugAssert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n parent = path;\n queryTarget.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n debugAssert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n parent = path.popLast();\n queryTarget.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n queryTarget.parent = toQueryPath(serializer, parent);\n\n const where = toFilters(target.filters);\n if (where) {\n queryTarget.structuredQuery!.where = where;\n }\n\n const orderBy = toOrder(target.orderBy);\n if (orderBy) {\n queryTarget.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = toInt32Proto(serializer, target.limit);\n if (limit !== null) {\n queryTarget.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n queryTarget.structuredQuery!.startAt = toStartAtCursor(target.startAt);\n }\n if (target.endAt) {\n queryTarget.structuredQuery!.endAt = toEndAtCursor(target.endAt);\n }\n\n return { queryTarget, parent };\n}\n\nexport function toRunAggregationQueryRequest(\n serializer: JsonProtoSerializer,\n target: Target,\n aggregates: Aggregate[]\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record<string, string>;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record<string, string> = {};\n\n const aggregations: ProtoAggregation[] = [];\n let aggregationNum = 0;\n\n aggregates.forEach(aggregate => {\n // Map all client-side aliases to a unique short-form\n // alias. This avoids issues with client-side aliases that\n // exceed the 1500-byte string size limit.\n const serverAlias = `aggregate_${aggregationNum++}`;\n aliasMap[serverAlias] = aggregate.alias;\n\n if (aggregate.aggregateType === 'count') {\n aggregations.push({\n alias: serverAlias,\n count: {}\n });\n } else if (aggregate.aggregateType === 'avg') {\n aggregations.push({\n alias: serverAlias,\n avg: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n } else if (aggregate.aggregateType === 'sum') {\n aggregations.push({\n alias: serverAlias,\n sum: {\n field: toFieldPathReference(aggregate.fieldPath!)\n }\n });\n }\n });\n\n return {\n request: {\n structuredAggregationQuery: {\n aggregations,\n structuredQuery: queryTarget.structuredQuery\n },\n parent: queryTarget.parent\n },\n aliasMap,\n parent\n };\n}\n\nexport function convertQueryTargetToQuery(target: ProtoQueryTarget): Query {\n let path = 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 hardAssert(\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 = fromFilters(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = fromInt32Proto(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = fromStartAtCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = fromEndAtCursor(query.endAt);\n }\n\n return newQuery(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n );\n}\n\nexport function fromQueryTarget(target: ProtoQueryTarget): Target {\n return queryToTarget(convertQueryTargetToQuery(target));\n}\n\nexport function toListenRequestLabels(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoApiClientObjectMap<string> | null {\n const value = toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n}\n\nexport function 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.ExistenceFilterMismatchBloom:\n return 'existence-filter-mismatch-bloom';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n}\n\nexport function toTarget(\n serializer: JsonProtoSerializer,\n targetData: TargetData\n): ProtoTarget {\n let result: ProtoTarget;\n const target = targetData.target;\n\n if (targetIsDocumentTarget(target)) {\n result = { documents: toDocumentsTarget(serializer, target) };\n } else {\n result = { query: toQueryTarget(serializer, target).queryTarget };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = toBytes(serializer, targetData.resumeToken);\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n } else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n result.readTime = toTimestamp(\n serializer,\n targetData.snapshotVersion.toTimestamp()\n );\n const expectedCount = toInt32Proto(serializer, targetData.expectedCount);\n if (expectedCount !== null) {\n result.expectedCount = expectedCount;\n }\n }\n\n return result;\n}\n\nfunction toFilters(filters: Filter[]): ProtoFilter | undefined {\n if (filters.length === 0) {\n return;\n }\n\n return toFilter(CompositeFilter.create(filters, CompositeOperator.AND));\n}\n\nfunction fromFilters(filter: ProtoFilter): Filter[] {\n const result = fromFilter(filter);\n\n if (\n result instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(result)\n ) {\n return result.getFilters();\n }\n\n return [result];\n}\n\nfunction fromFilter(filter: ProtoFilter): Filter {\n if (filter.unaryFilter !== undefined) {\n return fromUnaryFilter(filter);\n } else if (filter.fieldFilter !== undefined) {\n return fromFieldFilter(filter);\n } else if (filter.compositeFilter !== undefined) {\n return fromCompositeFilter(filter);\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n}\n\nfunction toOrder(orderBys: OrderBy[]): ProtoOrder[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => toPropertyOrder(order));\n}\n\nfunction fromOrder(orderBys: ProtoOrder[]): OrderBy[] {\n return orderBys.map(order => fromPropertyOrder(order));\n}\n\nfunction toStartAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction toEndAtCursor(cursor: Bound): ProtoCursor {\n return {\n before: !cursor.inclusive,\n values: cursor.position\n };\n}\n\nfunction fromStartAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !!cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\nfunction fromEndAtCursor(cursor: ProtoCursor): Bound {\n const inclusive = !cursor.before;\n const position = cursor.values || [];\n return new Bound(position, inclusive);\n}\n\n// visible for testing\nexport function toDirection(dir: Direction): ProtoOrderDirection {\n return DIRECTIONS[dir];\n}\n\n// visible for testing\nexport function fromDirection(\n dir: ProtoOrderDirection | undefined\n): 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\nexport function toOperatorName(op: Operator): ProtoFieldFilterOp {\n return OPERATORS[op];\n}\n\nexport function toCompositeOperatorName(\n op: CompositeOperator\n): ProtoCompositeFilterOp {\n return COMPOSITE_OPERATORS[op];\n}\n\nexport function fromOperatorName(op: ProtoFieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'NOT_EQUAL':\n return Operator.NOT_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 'NOT_IN':\n return Operator.NOT_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\nexport function fromCompositeOperatorName(\n op: ProtoCompositeFilterOp\n): CompositeOperator {\n switch (op) {\n case 'AND':\n return CompositeOperator.AND;\n case 'OR':\n return CompositeOperator.OR;\n default:\n return fail('Unknown operator');\n }\n}\n\nexport function toFieldPathReference(path: FieldPath): ProtoFieldReference {\n return { fieldPath: path.canonicalString() };\n}\n\nexport function fromFieldPathReference(\n fieldReference: ProtoFieldReference\n): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n}\n\n// visible for testing\nexport function toPropertyOrder(orderBy: OrderBy): ProtoOrder {\n return {\n field: toFieldPathReference(orderBy.field),\n direction: toDirection(orderBy.dir)\n };\n}\n\nexport function fromPropertyOrder(orderBy: ProtoOrder): OrderBy {\n return new OrderBy(\n fromFieldPathReference(orderBy.field!),\n fromDirection(orderBy.direction)\n );\n}\n\n// visible for testing\nexport function toFilter(filter: Filter): ProtoFilter {\n if (filter instanceof FieldFilter) {\n return toUnaryOrFieldFilter(filter);\n } else if (filter instanceof CompositeFilter) {\n return toCompositeFilter(filter);\n } else {\n return fail('Unrecognized filter type ' + JSON.stringify(filter));\n }\n}\n\nexport function toCompositeFilter(filter: CompositeFilter): ProtoFilter {\n const protos = filter.getFilters().map(filter => toFilter(filter));\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: toCompositeOperatorName(filter.op),\n filters: protos\n }\n };\n}\n\nexport function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter {\n if (filter.op === Operator.EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n } else if (filter.op === Operator.NOT_EQUAL) {\n if (isNanValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NAN'\n }\n };\n } else if (isNullValue(filter.value)) {\n return {\n unaryFilter: {\n field: toFieldPathReference(filter.field),\n op: 'IS_NOT_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: toFieldPathReference(filter.field),\n op: toOperatorName(filter.op),\n value: filter.value\n }\n };\n}\n\nexport function fromUnaryFilter(filter: ProtoFilter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nanField, Operator.EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NULL':\n const nullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(nullField, Operator.EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'IS_NOT_NAN':\n const notNanField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNanField, Operator.NOT_EQUAL, {\n doubleValue: NaN\n });\n case 'IS_NOT_NULL':\n const notNullField = fromFieldPathReference(filter.unaryFilter!.field!);\n return FieldFilter.create(notNullField, Operator.NOT_EQUAL, {\n nullValue: 'NULL_VALUE'\n });\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n}\n\nexport function fromFieldFilter(filter: ProtoFilter): FieldFilter {\n return FieldFilter.create(\n fromFieldPathReference(filter.fieldFilter!.field!),\n fromOperatorName(filter.fieldFilter!.op!),\n filter.fieldFilter!.value!\n );\n}\n\nexport function fromCompositeFilter(filter: ProtoFilter): CompositeFilter {\n return CompositeFilter.create(\n filter.compositeFilter!.filters!.map(filter => fromFilter(filter)),\n fromCompositeOperatorName(filter.compositeFilter!.op!)\n );\n}\n\nexport function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n}\n\nexport function fromDocumentMask(proto: ProtoDocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n return new FieldMask(paths.map(path => FieldPath.fromServerFormat(path)));\n}\n\nexport function 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 * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { ByteString } from '../util/byte_string';\n\n/** An enumeration of the different purposes we have for targets. */\nexport const enum TargetPurpose {\n /** A regular, normal query target. */\n Listen = 'TargetPurposeListen',\n\n /**\n * The query target was used to refill a query after an existence filter\n * mismatch.\n */\n ExistenceFilterMismatch = 'TargetPurposeExistenceFilterMismatch',\n\n /**\n * The query target was used if the query is the result of a false positive in\n * the bloom filter.\n */\n ExistenceFilterMismatchBloom = 'TargetPurposeExistenceFilterMismatchBloom',\n\n /** The query target was used to resolve a limbo document. */\n LimboResolution = 'TargetPurposeLimboResolution'\n}\n\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */\nexport class TargetData {\n constructor(\n /** The target being listened to. */\n readonly target: Target,\n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n readonly targetId: TargetId,\n /** The purpose of the target. */\n readonly purpose: TargetPurpose,\n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n readonly sequenceNumber: ListenSequenceNumber,\n /** The latest snapshot version seen for this target. */\n readonly snapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */\n readonly lastLimboFreeSnapshotVersion: SnapshotVersion = SnapshotVersion.min(),\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n readonly resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /**\n * The number of documents that last matched the query at the resume token or\n * read time. Documents are counted only when making a listen request with\n * resume token or read time, otherwise, keep it null.\n */\n readonly expectedCount: number | null = null\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 this.expectedCount\n );\n }\n\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */\n withResumeToken(\n resumeToken: ByteString,\n snapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n resumeToken,\n /* expectedCount= */ null\n );\n }\n\n /**\n * Creates a new target data instance with an updated expected count.\n */\n withExpectedCount(expectedCount: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken,\n expectedCount\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 this.expectedCount\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Timestamp } from '../api/timestamp';\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport { LimitType, Query, queryWithLimit } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetIsDocumentTarget } from '../core/target';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n IndexOffset,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { Overlay } from '../model/overlay';\nimport { FieldPath } from '../model/path';\nimport {\n BundledQuery as ProtoBundledQuery,\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { DocumentsTarget as PublicDocumentsTarget } from '../protos/firestore_proto_api';\nimport {\n convertQueryTargetToQuery,\n fromDocument,\n fromDocumentsTarget,\n fromMutation,\n fromQueryTarget,\n fromVersion,\n JsonProtoSerializer,\n toDocument,\n toDocumentsTarget,\n toMutation,\n toQueryTarget\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport {\n DbBundle,\n DbDocumentOverlay,\n DbIndexConfiguration,\n DbIndexState,\n DbMutationBatch,\n DbNamedQuery,\n DbQuery,\n DbRemoteDocument,\n DbTarget,\n DbTimestamp\n} from './indexeddb_schema';\nimport { DbDocumentOverlayKey, DbTimestampKey } from './indexeddb_sentinels';\nimport { TargetData, TargetPurpose } from './target_data';\n\n/** Serializer for values stored in the LocalStore. */\nexport class LocalSerializer {\n constructor(readonly remoteSerializer: JsonProtoSerializer) {}\n}\n\n/** Decodes a remote document from storage locally to a Document. */\nexport function fromDbRemoteDocument(\n localSerializer: LocalSerializer,\n remoteDoc: DbRemoteDocument\n): MutableDocument {\n let doc: MutableDocument;\n if (remoteDoc.document) {\n doc = fromDocument(\n localSerializer.remoteSerializer,\n remoteDoc.document,\n !!remoteDoc.hasCommittedMutations\n );\n } else if (remoteDoc.noDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n const version = fromDbTimestamp(remoteDoc.noDocument.readTime);\n doc = MutableDocument.newNoDocument(key, version);\n if (remoteDoc.hasCommittedMutations) {\n doc.setHasCommittedMutations();\n }\n } else if (remoteDoc.unknownDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n const version = fromDbTimestamp(remoteDoc.unknownDocument.version);\n doc = MutableDocument.newUnknownDocument(key, version);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n\n if (remoteDoc.readTime) {\n doc.setReadTime(fromDbTimestampKey(remoteDoc.readTime));\n }\n\n return doc;\n}\n\n/** Encodes a document for storage locally. */\nexport function toDbRemoteDocument(\n localSerializer: LocalSerializer,\n document: MutableDocument\n): DbRemoteDocument {\n const key = document.key;\n const remoteDoc: DbRemoteDocument = {\n prefixPath: key.getCollectionPath().popLast().toArray(),\n collectionGroup: key.collectionGroup,\n documentId: key.path.lastSegment(),\n readTime: toDbTimestampKey(document.readTime),\n hasCommittedMutations: document.hasCommittedMutations\n };\n\n if (document.isFoundDocument()) {\n remoteDoc.document = toDocument(localSerializer.remoteSerializer, document);\n } else if (document.isNoDocument()) {\n remoteDoc.noDocument = {\n path: key.path.toArray(),\n readTime: toDbTimestamp(document.version)\n };\n } else if (document.isUnknownDocument()) {\n remoteDoc.unknownDocument = {\n path: key.path.toArray(),\n version: toDbTimestamp(document.version)\n };\n } else {\n return fail('Unexpected Document ' + document);\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, 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/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\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 = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n ).queryTarget;\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\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 PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n uid: string,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid,\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n DbBundlesKey,\n DbBundleStore,\n DbNamedQueriesKey,\n DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbBundle,\n fromDbNamedQuery,\n toDbBundle,\n toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise<BundleMetadata | undefined> {\n return bundlesStore(transaction)\n .get(bundleId)\n .next(bundle => {\n if (bundle) {\n return fromDbBundle(bundle);\n }\n return undefined;\n });\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise<void> {\n return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise<NamedQuery | undefined> {\n return namedQueriesStore(transaction)\n .get(queryName)\n .next(query => {\n if (query) {\n return fromDbNamedQuery(query);\n }\n return undefined;\n });\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise<void> {\n return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbBundlesKey, DbBundle> {\n return getStore<DbBundlesKey, DbBundle>(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbNamedQueriesKey, DbNamedQuery> {\n return getStore<DbNamedQueriesKey, DbNamedQuery>(txn, DbNamedQueryStore);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport {\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayKey,\n DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbDocumentOverlay,\n LocalSerializer,\n toDbDocumentOverlay,\n toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(\n private readonly serializer: LocalSerializer,\n private readonly userId: string\n ) {}\n\n static forUser(\n serializer: LocalSerializer,\n user: User\n ): IndexedDbDocumentOverlayCache {\n const userId = user.uid || '';\n return new IndexedDbDocumentOverlayCache(serializer, userId);\n }\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<Overlay | null> {\n return documentOverlayStore(transaction)\n .get(toDbDocumentOverlayKey(this.userId, key))\n .next(dbOverlay => {\n if (dbOverlay) {\n return fromDbDocumentOverlay(this.serializer, dbOverlay);\n }\n return null;\n });\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n return this.getOverlay(transaction, key).next(overlay => {\n if (overlay !== null) {\n result.set(key, overlay);\n }\n });\n }).next(() => result);\n }\n\n saveOverlays(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n overlays: MutationMap\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n overlays.forEach((_, mutation) => {\n const overlay = new Overlay(largestBatchId, mutation);\n promises.push(this.saveOverlay(transaction, overlay));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise<void> {\n const collectionPaths = new Set<string>();\n\n // Get the set of unique collection paths.\n documentKeys.forEach(key =>\n collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n );\n\n const promises: Array<PersistencePromise<void>> = [];\n collectionPaths.forEach(collectionPath => {\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, batchId],\n [this.userId, collectionPath, batchId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n promises.push(\n documentOverlayStore(transaction).deleteAll(\n DbDocumentOverlayCollectionPathOverlayIndex,\n range\n )\n );\n });\n return PersistencePromise.waitFor(promises);\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n const collectionPath = encodeResourcePath(collection);\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, sinceBatchId],\n [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n .next(dbOverlays => {\n for (const dbOverlay of dbOverlays) {\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n result.set(overlay.getKey(), overlay);\n }\n return result;\n });\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n let currentBatchId: number | undefined = undefined;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionGroup, sinceBatchId],\n [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .iterate(\n {\n index: DbDocumentOverlayCollectionGroupOverlayIndex,\n range\n },\n (_, dbOverlay, control) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n if (\n result.size() < count ||\n overlay.largestBatchId === currentBatchId\n ) {\n result.set(overlay.getKey(), overlay);\n currentBatchId = overlay.largestBatchId;\n } else {\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n overlay: Overlay\n ): PersistencePromise<void> {\n return documentOverlayStore(transaction).put(\n toDbDocumentOverlay(this.serializer, this.userId, overlay)\n );\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbDocumentOverlayKey, DbDocumentOverlay> {\n return getStore<DbDocumentOverlayKey, DbDocumentOverlay>(\n txn,\n DbDocumentOverlayStore\n );\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { normalizeByteString, normalizeNumber } from '../model/normalize';\nimport { isMaxValue } from '../model/values';\nimport { ArrayValue, MapValue, Value } from '../protos/firestore_proto_api';\nimport { fail } from '../util/assert';\nimport { isNegativeZero } from '../util/types';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\n\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n\nconst INDEX_TYPE_NULL = 5;\nconst INDEX_TYPE_BOOLEAN = 10;\nconst INDEX_TYPE_NAN = 13;\nconst INDEX_TYPE_NUMBER = 15;\nconst INDEX_TYPE_TIMESTAMP = 20;\nconst INDEX_TYPE_STRING = 25;\nconst INDEX_TYPE_BLOB = 30;\nconst INDEX_TYPE_REFERENCE = 37;\nconst INDEX_TYPE_GEOPOINT = 45;\nconst INDEX_TYPE_ARRAY = 50;\nconst INDEX_TYPE_MAP = 55;\nconst INDEX_TYPE_REFERENCE_SEGMENT = 60;\n\n// A terminator that indicates that a truncatable value was not truncated.\n// This must be smaller than all other type labels.\nconst NOT_TRUNCATED = 2;\n\n/** Firestore index value writer. */\nexport class FirestoreIndexValueWriter {\n static INSTANCE = new FirestoreIndexValueWriter();\n\n private constructor() {}\n\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n //\n // As an example, consider the resulting encoding for:\n //\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n\n /** Writes an index value. */\n writeIndexValue(value: Value, encoder: DirectionalIndexByteEncoder): void {\n this.writeIndexValueAux(value, encoder);\n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n encoder.writeInfinity();\n }\n\n private writeIndexValueAux(\n indexValue: Value,\n encoder: DirectionalIndexByteEncoder\n ): void {\n if ('nullValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NULL);\n } else if ('booleanValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BOOLEAN);\n encoder.writeNumber(indexValue.booleanValue ? 1 : 0);\n } else if ('integerValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n encoder.writeNumber(normalizeNumber(indexValue.integerValue));\n } else if ('doubleValue' in indexValue) {\n const n = normalizeNumber(indexValue.doubleValue);\n if (isNaN(n)) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NAN);\n } else {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n if (isNegativeZero(n)) {\n // -0.0, 0 and 0.0 are all considered the same\n encoder.writeNumber(0.0);\n } else {\n encoder.writeNumber(n);\n }\n }\n } else if ('timestampValue' in indexValue) {\n const timestamp = indexValue.timestampValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_TIMESTAMP);\n if (typeof timestamp === 'string') {\n encoder.writeString(timestamp);\n } else {\n encoder.writeString(`${timestamp.seconds || ''}`);\n encoder.writeNumber(timestamp.nanos || 0);\n }\n } else if ('stringValue' in indexValue) {\n this.writeIndexString(indexValue.stringValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else if ('bytesValue' in indexValue) {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_BLOB);\n encoder.writeBytes(normalizeByteString(indexValue.bytesValue!));\n this.writeTruncationMarker(encoder);\n } else if ('referenceValue' in indexValue) {\n this.writeIndexEntityRef(indexValue.referenceValue!, encoder);\n } else if ('geoPointValue' in indexValue) {\n const geoPoint = indexValue.geoPointValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_GEOPOINT);\n encoder.writeNumber(geoPoint.latitude || 0);\n encoder.writeNumber(geoPoint.longitude || 0);\n } else if ('mapValue' in indexValue) {\n if (isMaxValue(indexValue)) {\n this.writeValueTypeLabel(encoder, Number.MAX_SAFE_INTEGER);\n } else {\n this.writeIndexMap(indexValue.mapValue!, encoder);\n this.writeTruncationMarker(encoder);\n }\n } else if ('arrayValue' in indexValue) {\n this.writeIndexArray(indexValue.arrayValue!, encoder);\n this.writeTruncationMarker(encoder);\n } else {\n fail('unknown index value type ' + indexValue);\n }\n }\n\n private writeIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_STRING);\n this.writeUnlabeledIndexString(stringIndexValue, encoder);\n }\n\n private writeUnlabeledIndexString(\n stringIndexValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n encoder.writeString(stringIndexValue);\n }\n\n private writeIndexMap(\n mapIndexValue: MapValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const map = mapIndexValue.fields || {};\n this.writeValueTypeLabel(encoder, INDEX_TYPE_MAP);\n for (const key of Object.keys(map)) {\n this.writeIndexString(key, encoder);\n this.writeIndexValueAux(map[key], encoder);\n }\n }\n\n private writeIndexArray(\n arrayIndexValue: ArrayValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const values = arrayIndexValue.values || [];\n this.writeValueTypeLabel(encoder, INDEX_TYPE_ARRAY);\n for (const element of values) {\n this.writeIndexValueAux(element, encoder);\n }\n }\n\n private writeIndexEntityRef(\n referenceValue: string,\n encoder: DirectionalIndexByteEncoder\n ): void {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE);\n const path = DocumentKey.fromName(referenceValue).path;\n path.forEach(segment => {\n this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE_SEGMENT);\n this.writeUnlabeledIndexString(segment, encoder);\n });\n }\n\n private writeValueTypeLabel(\n encoder: DirectionalIndexByteEncoder,\n typeOrder: number\n ): void {\n encoder.writeNumber(typeOrder);\n }\n\n private writeTruncationMarker(encoder: DirectionalIndexByteEncoder): void {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n encoder.writeNumber(NOT_TRUNCATED);\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law | agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n/** These constants are taken from the backend. */\nconst MIN_SURROGATE = '\\uD800';\nconst MAX_SURROGATE = '\\uDBFF';\n\nconst ESCAPE1 = 0x00;\nconst NULL_BYTE = 0xff; // Combined with ESCAPE1\nconst SEPARATOR = 0x01; // Combined with ESCAPE1\n\nconst ESCAPE2 = 0xff;\nconst INFINITY = 0xff; // Combined with ESCAPE2\nconst FF_BYTE = 0x00; // Combined with ESCAPE2\n\nconst LONG_SIZE = 64;\nconst BYTE_SIZE = 8;\n\n/**\n * The default size of the buffer. This is arbitrary, but likely larger than\n * most index values so that less copies of the underlying buffer will be made.\n * For large values, a single copy will made to double the buffer length.\n */\nconst DEFAULT_BUFFER_SIZE = 1024;\n\n/** Converts a JavaScript number to a byte array (using big endian encoding). */\nfunction doubleToLongBits(value: number): Uint8Array {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value, /* littleEndian= */ false);\n return new Uint8Array(dv.buffer);\n}\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nexport function numberOfLeadingZerosInByte(x: number): number {\n debugAssert(x < 256, 'Provided value is not a byte: ' + x);\n if (x === 0) {\n return 8;\n }\n\n let zeros = 0;\n if (x >> 4 === 0) {\n // Test if the first four bits are zero.\n zeros += 4;\n x = x << 4;\n }\n if (x >> 6 === 0) {\n // Test if the first two (or next two) bits are zero.\n zeros += 2;\n x = x << 2;\n }\n if (x >> 7 === 0) {\n // Test if the remaining bit is zero.\n zeros += 1;\n }\n return zeros;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\nfunction numberOfLeadingZeros(bytes: Uint8Array): number {\n debugAssert(\n bytes.length === 8,\n 'Can only count leading zeros in 64-bit numbers'\n );\n let leadingZeros = 0;\n for (let i = 0; i < 8; ++i) {\n const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff);\n leadingZeros += zeros;\n if (zeros !== 8) {\n break;\n }\n }\n return leadingZeros;\n}\n\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction unsignedNumLength(value: Uint8Array): number {\n // This is just the number of bytes for the unsigned representation of the number.\n const numBits = LONG_SIZE - numberOfLeadingZeros(value);\n return Math.ceil(numBits / BYTE_SIZE);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */\nexport class OrderedCodeWriter {\n buffer = new Uint8Array(DEFAULT_BUFFER_SIZE);\n position = 0;\n\n writeBytesAscending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteAscending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorAscending();\n }\n\n writeBytesDescending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteDescending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorDescending();\n }\n\n /** Writes utf8 bytes into this byte sequence, ascending. */\n writeUtf8Ascending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteAscending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteAscending((0x0f << 6) | (charCode >>> 6));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteAscending((0x0f << 5) | (charCode >>> 12));\n this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteAscending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorAscending();\n }\n\n /** Writes utf8 bytes into this byte sequence, descending */\n writeUtf8Descending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteDescending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteDescending((0x0f << 6) | (charCode >>> 6));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteDescending((0x0f << 5) | (charCode >>> 12));\n this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteDescending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorDescending();\n }\n\n writeNumberAscending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = len & 0xff; // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = value[i] & 0xff;\n }\n }\n\n writeNumberDescending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = ~(len & 0xff); // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = ~(value[i] & 0xff);\n }\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */\n writeInfinityAscending(): void {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(INFINITY);\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */\n writeInfinityDescending(): void {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(INFINITY);\n }\n\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */\n reset(): void {\n this.position = 0;\n }\n\n seed(encodedBytes: Uint8Array): void {\n this.ensureAvailable(encodedBytes.length);\n this.buffer.set(encodedBytes, this.position);\n this.position += encodedBytes.length;\n }\n\n /** Makes a copy of the encoded bytes in this buffer. */\n encodedBytes(): Uint8Array {\n return this.buffer.slice(0, this.position);\n }\n\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */\n private toOrderedBits(val: number): Uint8Array {\n const value = doubleToLongBits(val);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n const isNegative = (value[0] & 0x80) !== 0;\n\n // Revert the two complement to get natural ordering\n value[0] ^= isNegative ? 0xff : 0x80;\n for (let i = 1; i < value.length; ++i) {\n value[i] ^= isNegative ? 0xff : 0x00;\n }\n return value;\n }\n\n /** Writes a single byte ascending to the buffer. */\n private writeByteAscending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(FF_BYTE);\n } else {\n this.writeEscapedByteAscending(masked);\n }\n }\n\n /** Writes a single byte descending to the buffer. */\n private writeByteDescending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(FF_BYTE);\n } else {\n this.writeEscapedByteDescending(b);\n }\n }\n\n private writeSeparatorAscending(): void {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(SEPARATOR);\n }\n\n private writeSeparatorDescending(): void {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(SEPARATOR);\n }\n\n private writeEscapedByteAscending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = b;\n }\n\n private writeEscapedByteDescending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = ~b;\n }\n\n private ensureAvailable(bytes: number): void {\n const minCapacity = bytes + this.position;\n if (minCapacity <= this.buffer.length) {\n return;\n }\n // Try doubling.\n let newLength = this.buffer.length * 2;\n // Still not big enough? Just allocate the right size.\n if (newLength < minCapacity) {\n newLength = minCapacity;\n }\n // Create the new buffer.\n const newBuffer = new Uint8Array(newLength);\n newBuffer.set(this.buffer); // copy old data\n this.buffer = newBuffer;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { IndexKind } from '../model/field_index';\nimport { ByteString } from '../util/byte_string';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\nimport { OrderedCodeWriter } from './ordered_code_writer';\n\nclass AscendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesAscending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Ascending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberAscending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityAscending();\n }\n}\n\nclass DescendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesDescending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Descending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberDescending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityDescending();\n }\n}\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */\nexport class IndexByteEncoder {\n private orderedCode = new OrderedCodeWriter();\n private ascending = new AscendingIndexByteEncoder(this.orderedCode);\n private descending = new DescendingIndexByteEncoder(this.orderedCode);\n\n seed(encodedBytes: Uint8Array): void {\n this.orderedCode.seed(encodedBytes);\n }\n\n forKind(kind: IndexKind): DirectionalIndexByteEncoder {\n return kind === IndexKind.ASCENDING ? this.ascending : this.descending;\n }\n\n encodedBytes(): Uint8Array {\n return this.orderedCode.encodedBytes();\n }\n\n reset(): void {\n this.orderedCode.reset();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\n\n/** Represents an index entry saved by the SDK in persisted storage. */\nexport class IndexEntry {\n constructor(\n readonly indexId: number,\n readonly documentKey: DocumentKey,\n readonly arrayValue: Uint8Array,\n readonly directionalValue: Uint8Array\n ) {}\n\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */\n successor(): IndexEntry {\n const currentLength = this.directionalValue.length;\n const newLength =\n currentLength === 0 || this.directionalValue[currentLength - 1] === 255\n ? currentLength + 1\n : currentLength;\n\n const successor = new Uint8Array(newLength);\n successor.set(this.directionalValue, 0);\n if (newLength !== currentLength) {\n successor.set([0], this.directionalValue.length);\n } else {\n ++successor[successor.length - 1];\n }\n\n return new IndexEntry(\n this.indexId,\n this.documentKey,\n this.arrayValue,\n successor\n );\n }\n}\n\nexport function indexEntryComparator(\n left: IndexEntry,\n right: IndexEntry\n): number {\n let cmp = left.indexId - right.indexId;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left.arrayValue, right.arrayValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left.directionalValue, right.directionalValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n return DocumentKey.comparator(left.documentKey, right.documentKey);\n}\n\nexport function compareByteArrays(left: Uint8Array, right: Uint8Array): number {\n for (let i = 0; i < left.length && i < right.length; ++i) {\n const compare = left[i] - right[i];\n if (compare !== 0) {\n return compare;\n }\n }\n return left.length - right.length;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldFilter, Operator } from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { Target } from '../core/target';\nimport { hardAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind,\n IndexSegment,\n IndexState\n} from './field_index';\nimport { FieldPath } from './path';\n\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */\nexport class TargetIndexMatcher {\n // The collection ID (or collection group) of the query target.\n private readonly collectionId: string;\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n private inequalityFilters = new SortedSet<FieldFilter>((lhs, rhs) =>\n FieldPath.comparator(lhs.field, rhs.field)\n );\n\n // The list of equality filters of the target.\n private readonly equalityFilters: FieldFilter[];\n // The list of orderBys of the target.\n private readonly orderBys: OrderBy[];\n\n constructor(target: Target) {\n this.collectionId =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n this.orderBys = target.orderBy;\n this.equalityFilters = [];\n for (const filter of target.filters) {\n const fieldFilter = filter as FieldFilter;\n if (fieldFilter.isInequality()) {\n this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n } else {\n this.equalityFilters.push(fieldFilter);\n }\n }\n }\n\n get hasMultipleInequality(): boolean {\n return this.inequalityFilters.size > 1;\n }\n\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */\n servedByIndex(index: FieldIndex): boolean {\n hardAssert(\n index.collectionGroup === this.collectionId,\n 'Collection IDs do not match'\n );\n\n if (this.hasMultipleInequality) {\n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return false;\n }\n\n // If there is an array element, find a matching filter.\n const arraySegment = fieldIndexGetArraySegment(index);\n if (\n arraySegment !== undefined &&\n !this.hasMatchingEqualityFilter(arraySegment)\n ) {\n return false;\n }\n\n const segments = fieldIndexGetDirectionalSegments(index);\n let equalitySegments = new Set<string>();\n let segmentIndex = 0;\n let orderBysIndex = 0;\n\n // Process all equalities first. Equalities can appear out of order.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n // We attempt to greedily match all segments to equality filters. If a\n // filter matches an index segment, we can mark the segment as used.\n if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n equalitySegments = equalitySegments.add(\n segments[segmentIndex].fieldPath.canonicalString()\n );\n } else {\n // If we cannot find a matching filter, we need to verify whether the\n // remaining segments map to the target's inequality and its orderBy\n // clauses.\n break;\n }\n }\n\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (segmentIndex === segments.length) {\n return true;\n }\n\n if (this.inequalityFilters.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n const segment = segments[segmentIndex];\n\n if (\n !this.matchesFilter(inequalityFilter, segment) ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n ++segmentIndex;\n }\n\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n const segment = segments[segmentIndex];\n if (\n orderBysIndex >= this.orderBys.length ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */\n buildTargetIndex(): FieldIndex | null {\n if (this.hasMultipleInequality) {\n return null;\n }\n\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let uniqueFields = new SortedSet<FieldPath>(FieldPath.comparator);\n const segments: IndexSegment[] = [];\n\n for (const filter of this.equalityFilters) {\n if (filter.field.isKeyField()) {\n continue;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n if (isArrayOperator) {\n segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n } else {\n if (uniqueFields.has(filter.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(filter.field);\n segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n }\n }\n\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const orderBy of this.orderBys) {\n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n if (orderBy.field.isKeyField()) {\n continue;\n }\n\n if (uniqueFields.has(orderBy.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(orderBy.field);\n\n segments.push(\n new IndexSegment(\n orderBy.field,\n orderBy.dir === Direction.ASCENDING\n ? IndexKind.ASCENDING\n : IndexKind.DESCENDING\n )\n );\n }\n\n return new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n this.collectionId,\n segments,\n IndexState.empty()\n );\n }\n\n private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n for (const filter of this.equalityFilters) {\n if (this.matchesFilter(filter, segment)) {\n return true;\n }\n }\n return false;\n }\n\n private matchesFilter(\n filter: FieldFilter | undefined,\n segment: IndexSegment\n ): boolean {\n if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n return false;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n }\n\n private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n if (!orderBy.field.isEqual(segment.fieldPath)) {\n return false;\n }\n return (\n (segment.kind === IndexKind.ASCENDING &&\n orderBy.dir === Direction.ASCENDING) ||\n (segment.kind === IndexKind.DESCENDING &&\n orderBy.dir === Direction.DESCENDING)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CompositeFilter,\n compositeFilterIsConjunction,\n compositeFilterIsDisjunction,\n compositeFilterIsFlat,\n compositeFilterIsFlatConjunction,\n compositeFilterWithAddedFilters,\n CompositeOperator,\n FieldFilter,\n Filter,\n InFilter,\n Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n if (filter instanceof InFilter) {\n const expandedFilters =\n filter.value.arrayValue?.values?.map(value =>\n FieldFilter.create(filter.field, Operator.EQUAL, value)\n ) || [];\n\n return CompositeFilter.create(expandedFilters, CompositeOperator.OR);\n } else {\n // We have reached other kinds of field filters.\n return filter;\n }\n }\n\n // We have a composite filter.\n const expandedFilters = filter.filters.map(subfilter =>\n computeInExpansion(subfilter)\n );\n return CompositeFilter.create(expandedFilters, filter.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n * <p>Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */\nexport function getDnfTerms(filter: CompositeFilter): Filter[] {\n if (filter.getFilters().length === 0) {\n return [];\n }\n\n const result: Filter = computeDistributedNormalForm(\n computeInExpansion(filter)\n );\n\n hardAssert(\n isDisjunctiveNormalForm(result),\n 'computeDistributedNormalForm did not result in disjunctive normal form'\n );\n\n if (isSingleFieldFilter(result) || isFlatConjunction(result)) {\n return [result];\n }\n\n return result.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */\nfunction isSingleFieldFilter(filter: Filter): boolean {\n return filter instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */\nfunction isFlatConjunction(filter: Filter): boolean {\n return (\n filter instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(filter)\n );\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n return (\n isSingleFieldFilter(filter) ||\n isFlatConjunction(filter) ||\n isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n filter: Filter\n): boolean {\n if (filter instanceof CompositeFilter) {\n if (compositeFilterIsDisjunction(filter)) {\n for (const subFilter of filter.getFilters()) {\n if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n if (filter.filters.length === 1) {\n return computeDistributedNormalForm(filter.filters[0]);\n }\n\n // Compute DNF for each of the subfilters first\n const result = filter.filters.map(subfilter =>\n computeDistributedNormalForm(subfilter)\n );\n\n let newFilter: Filter = CompositeFilter.create(result, filter.op);\n newFilter = applyAssociation(newFilter);\n\n if (isDisjunctiveNormalForm(newFilter)) {\n return newFilter;\n }\n\n hardAssert(\n newFilter instanceof CompositeFilter,\n 'field filters are already in DNF form'\n );\n hardAssert(\n compositeFilterIsConjunction(newFilter),\n 'Disjunction of filters all of which are already in DNF form is itself in DNF form.'\n );\n hardAssert(\n newFilter.filters.length > 1,\n 'Single-filter composite filters are already in DNF form.'\n );\n\n return newFilter.filters.reduce((runningResult, filter) =>\n applyDistribution(runningResult, filter)\n );\n}\n\nexport function applyDistribution(lhs: Filter, rhs: Filter): Filter {\n hardAssert(\n lhs instanceof FieldFilter || lhs instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n hardAssert(\n rhs instanceof FieldFilter || rhs instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n let result: Filter;\n\n if (lhs instanceof FieldFilter) {\n if (rhs instanceof FieldFilter) {\n // FieldFilter FieldFilter\n result = applyDistributionFieldFilters(lhs, rhs);\n } else {\n // FieldFilter CompositeFilter\n result = applyDistributionFieldAndCompositeFilters(lhs, rhs);\n }\n } else {\n if (rhs instanceof FieldFilter) {\n // CompositeFilter FieldFilter\n result = applyDistributionFieldAndCompositeFilters(rhs, lhs);\n } else {\n // CompositeFilter CompositeFilter\n result = applyDistributionCompositeFilters(lhs, rhs);\n }\n }\n\n return applyAssociation(result);\n}\n\nfunction applyDistributionFieldFilters(\n lhs: FieldFilter,\n rhs: FieldFilter\n): Filter {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([lhs, rhs], CompositeOperator.AND);\n}\n\nfunction applyDistributionCompositeFilters(\n lhs: CompositeFilter,\n rhs: CompositeFilter\n): Filter {\n hardAssert(\n lhs.filters.length > 0 && rhs.filters.length > 0,\n 'Found an empty composite filter'\n );\n\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n\n // Case 1 is a merge.\n if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {\n return compositeFilterWithAddedFilters(lhs, rhs.getFilters());\n }\n\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;\n const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;\n const results = disjunctionSide.filters.map(subfilter =>\n applyDistribution(subfilter, otherSide)\n );\n return CompositeFilter.create(results, CompositeOperator.OR);\n}\n\nfunction applyDistributionFieldAndCompositeFilters(\n fieldFilter: FieldFilter,\n compositeFilter: CompositeFilter\n): Filter {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (compositeFilterIsConjunction(compositeFilter)) {\n // Case 1\n return compositeFilterWithAddedFilters(\n compositeFilter,\n fieldFilter.getFilters()\n );\n } else {\n // Case 2\n const newFilters = compositeFilter.filters.map(subfilter =>\n applyDistribution(fieldFilter, subfilter)\n );\n\n return CompositeFilter.create(newFilters, CompositeOperator.OR);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n * <ul>\n * <li>A | (B | C) == (A | B) | C == (A | B | C)\n * <li>A & (B & C) == (A & B) & C == (A & B & C)\n * </ul>\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n const filters = filter.getFilters();\n\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (filters.length === 1) {\n return applyAssociation(filters[0]);\n }\n\n // Associativity applied to a flat composite filter results is itself.\n if (compositeFilterIsFlat(filter)) {\n return filter;\n }\n\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));\n\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n const newSubfilters: Filter[] = [];\n updatedFilters.forEach(subfilter => {\n if (subfilter instanceof FieldFilter) {\n newSubfilters.push(subfilter);\n } else if (subfilter instanceof CompositeFilter) {\n if (subfilter.op === filter.op) {\n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n newSubfilters.push(...subfilter.filters);\n } else {\n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n newSubfilters.push(subfilter);\n }\n }\n });\n\n if (newSubfilters.length === 1) {\n return newSubfilters[0];\n }\n\n return CompositeFilter.create(newSubfilters, filter.op);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\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 addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<DocumentKey[] | null> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<DocumentKey[] | null>(null);\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexType> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<IndexType>(IndexType.NONE);\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise<FieldIndex[]> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<FieldIndex[]>([]);\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise<string | null> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve<string | null>(null);\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise<void> {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */\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 debugAssert(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 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport {\n canonifyTarget,\n newTarget,\n Target,\n targetEquals,\n targetGetArrayValues,\n targetGetLowerBound,\n targetGetNotInValues,\n targetGetSegmentCount,\n targetGetUpperBound,\n targetHasLimit\n} from '../core/target';\nimport { FirestoreIndexValueWriter } from '../index/firestore_index_value_writer';\nimport { IndexByteEncoder } from '../index/index_byte_encoder';\nimport { IndexEntry, indexEntryComparator } from '../index/index_entry';\nimport { documentKeySet, DocumentMap } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n fieldIndexGetKeyOrder,\n fieldIndexToString,\n IndexKind,\n IndexOffset,\n indexOffsetComparator,\n IndexSegment\n} from '../model/field_index';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { TargetIndexMatcher } from '../model/target_index_matcher';\nimport { isArray, refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { getDnfTerms } from '../util/logic_utils';\nimport { immediateSuccessor, primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { diffSortedSets, SortedSet } from '../util/sorted_set';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexManager, IndexType } from './index_manager';\nimport {\n DbCollectionParent,\n DbIndexConfiguration,\n DbIndexEntry,\n DbIndexState\n} from './indexeddb_schema';\nimport {\n DbCollectionParentKey,\n DbCollectionParentStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationKey,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryKey,\n DbIndexEntryStore,\n DbIndexStateKey,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbIndexConfiguration,\n toDbIndexConfiguration,\n toDbIndexState\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nconst LOG_TAG = 'IndexedDbIndexManager';\n\nconst EMPTY_VALUE = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\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\n * used to satisfy reads.\n */\n private collectionParentsCache = new MemoryCollectionParentIndex();\n\n private readonly uid: string;\n\n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n private targetToDnfSubTargets = new ObjectMap<Target, Target[]>(\n t => canonifyTarget(t),\n (l, r) => targetEquals(l, r)\n );\n\n constructor(user: User, private readonly databaseId: DatabaseId) {\n this.uid = user.uid || '';\n }\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 debugAssert(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: encodeResourcePath(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(decodeResourcePath(entry.parent));\n }\n return parentPaths;\n });\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const indexes = indexConfigurationStore(transaction);\n const dbIndex = toDbIndexConfiguration(index);\n delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb\n const result = indexes.add(dbIndex);\n if (index.indexState) {\n const states = indexStateStore(transaction);\n return result.next(indexId => {\n states.put(\n toDbIndexState(\n indexId,\n this.uid,\n index.indexState.sequenceNumber,\n index.indexState.offset\n )\n );\n });\n } else {\n return result.next();\n }\n }\n\n deleteFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n const entries = indexEntriesStore(transaction);\n return indexes\n .delete(index.indexId)\n .next(() =>\n states.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n )\n .next(() =>\n entries.delete(\n IDBKeyRange.bound(\n [index.indexId],\n [index.indexId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n )\n )\n );\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const entries = indexEntriesStore(transaction);\n const states = indexStateStore(transaction);\n\n return indexes\n .deleteAll()\n .next(() => entries.deleteAll())\n .next(() => states.deleteAll());\n }\n\n createTargetIndexes(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getIndexType(transaction, subTarget).next(type => {\n if (type === IndexType.NONE || type === IndexType.PARTIAL) {\n const targetIndexMatcher = new TargetIndexMatcher(subTarget);\n const fieldIndex = targetIndexMatcher.buildTargetIndex();\n if (fieldIndex != null) {\n return this.addFieldIndex(transaction, fieldIndex);\n }\n }\n });\n }\n );\n }\n\n getDocumentsMatchingTarget(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<DocumentKey[] | null> {\n const indexEntries = indexEntriesStore(transaction);\n\n let canServeTarget = true;\n const indexes = new Map<Target, FieldIndex | null>();\n\n return PersistencePromise.forEach(\n this.getSubTargets(target),\n (subTarget: Target) => {\n return this.getFieldIndex(transaction, subTarget).next(index => {\n canServeTarget &&= !!index;\n indexes.set(subTarget, index);\n });\n }\n ).next(() => {\n if (!canServeTarget) {\n return PersistencePromise.resolve(null as DocumentKey[] | null);\n } else {\n let existingKeys = documentKeySet();\n const result: DocumentKey[] = [];\n return PersistencePromise.forEach(indexes, (index, subTarget) => {\n logDebug(\n LOG_TAG,\n `Using index ${fieldIndexToString(\n index!\n )} to execute ${canonifyTarget(target)}`\n );\n\n const arrayValues = targetGetArrayValues(subTarget, index!);\n const notInValues = targetGetNotInValues(subTarget, index!);\n const lowerBound = targetGetLowerBound(subTarget, index!);\n const upperBound = targetGetUpperBound(subTarget, index!);\n\n const lowerBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n lowerBound\n );\n const upperBoundEncoded = this.encodeBound(\n index!,\n subTarget,\n upperBound\n );\n const notInEncoded = this.encodeValues(\n index!,\n subTarget,\n notInValues\n );\n\n const indexRanges = this.generateIndexRanges(\n index!.indexId,\n arrayValues,\n lowerBoundEncoded,\n lowerBound.inclusive,\n upperBoundEncoded,\n upperBound.inclusive,\n notInEncoded\n );\n return PersistencePromise.forEach(\n indexRanges,\n (indexRange: IDBKeyRange) => {\n return indexEntries\n .loadFirst(indexRange, target.limit)\n .next(entries => {\n entries.forEach(entry => {\n const documentKey = DocumentKey.fromSegments(\n entry.documentKey\n );\n if (!existingKeys.has(documentKey)) {\n existingKeys = existingKeys.add(documentKey);\n result.push(documentKey);\n }\n });\n });\n }\n );\n }).next(() => result as DocumentKey[] | null);\n }\n });\n }\n\n private getSubTargets(target: Target): Target[] {\n let subTargets = this.targetToDnfSubTargets.get(target);\n if (subTargets) {\n return subTargets;\n }\n\n if (target.filters.length === 0) {\n subTargets = [target];\n } else {\n // There is an implicit AND operation between all the filters stored in the target\n const dnf: Filter[] = getDnfTerms(\n CompositeFilter.create(target.filters, CompositeOperator.AND)\n );\n\n subTargets = dnf.map(term =>\n newTarget(\n target.path,\n target.collectionGroup,\n target.orderBy,\n term.getFilters(),\n target.limit,\n target.startAt,\n target.endAt\n )\n );\n }\n\n this.targetToDnfSubTargets.set(target, subTargets);\n return subTargets;\n }\n\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */\n private generateIndexRanges(\n indexId: number,\n arrayValues: ProtoValue[] | null,\n lowerBounds: Uint8Array[],\n lowerBoundInclusive: boolean,\n upperBounds: Uint8Array[],\n upperBoundInclusive: boolean,\n notInValues: Uint8Array[]\n ): IDBKeyRange[] {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const totalScans =\n (arrayValues != null ? arrayValues.length : 1) *\n Math.max(lowerBounds.length, upperBounds.length);\n const scansPerArrayElement =\n totalScans / (arrayValues != null ? arrayValues.length : 1);\n\n const indexRanges: IDBKeyRange[] = [];\n for (let i = 0; i < totalScans; ++i) {\n const arrayValue = arrayValues\n ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement])\n : EMPTY_VALUE;\n\n const lowerBound = this.generateLowerBound(\n indexId,\n arrayValue,\n lowerBounds[i % scansPerArrayElement],\n lowerBoundInclusive\n );\n const upperBound = this.generateUpperBound(\n indexId,\n arrayValue,\n upperBounds[i % scansPerArrayElement],\n upperBoundInclusive\n );\n\n const notInBound = notInValues.map(notIn =>\n this.generateLowerBound(\n indexId,\n arrayValue,\n notIn,\n /* inclusive= */ true\n )\n );\n\n indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound));\n }\n\n return indexRanges;\n }\n\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */\n private generateLowerBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry : entry.successor();\n }\n\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */\n private generateUpperBound(\n indexId: number,\n arrayValue: Uint8Array,\n directionalValue: Uint8Array,\n inclusive: boolean\n ): IndexEntry {\n const entry = new IndexEntry(\n indexId,\n DocumentKey.empty(),\n arrayValue,\n directionalValue\n );\n return inclusive ? entry.successor() : entry;\n }\n\n private getFieldIndex(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<FieldIndex | null> {\n const targetIndexMatcher = new TargetIndexMatcher(target);\n const collectionGroup =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n\n return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {\n // Return the index with the most number of segments.\n let index: FieldIndex | null = null;\n for (const candidate of indexes) {\n const matches = targetIndexMatcher.servedByIndex(candidate);\n if (\n matches &&\n (!index || candidate.fields.length > index.fields.length)\n ) {\n index = candidate;\n }\n }\n return index;\n });\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexType> {\n let indexType = IndexType.FULL;\n const subTargets = this.getSubTargets(target);\n return PersistencePromise.forEach(subTargets, (target: Target) => {\n return this.getFieldIndex(transaction, target).next(index => {\n if (!index) {\n indexType = IndexType.NONE;\n } else if (\n indexType !== IndexType.NONE &&\n index.fields.length < targetGetSegmentCount(target)\n ) {\n indexType = IndexType.PARTIAL;\n }\n });\n }).next(() => {\n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n if (\n targetHasLimit(target) &&\n subTargets.length > 1 &&\n indexType === IndexType.FULL\n ) {\n return IndexType.PARTIAL;\n }\n\n return indexType;\n });\n }\n\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */\n private encodeDirectionalElements(\n fieldIndex: FieldIndex,\n document: Document\n ): Uint8Array | null {\n const encoder = new IndexByteEncoder();\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const field = document.data.field(segment.fieldPath);\n if (field == null) {\n return null;\n }\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n field,\n directionalEncoder\n );\n }\n return encoder.encodedBytes();\n }\n\n /** Encodes a single value to the ascending index format. */\n private encodeSingleElement(value: ProtoValue): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n encoder.forKind(IndexKind.ASCENDING)\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */\n private encodeDirectionalKey(\n fieldIndex: FieldIndex,\n documentKey: DocumentKey\n ): Uint8Array {\n const encoder = new IndexByteEncoder();\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n refValue(this.databaseId, documentKey),\n encoder.forKind(fieldIndexGetKeyOrder(fieldIndex))\n );\n return encoder.encodedBytes();\n }\n\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */\n private encodeValues(\n fieldIndex: FieldIndex,\n target: Target,\n values: ProtoValue[] | null\n ): Uint8Array[] {\n if (values === null) {\n return [];\n }\n\n let encoders: IndexByteEncoder[] = [];\n encoders.push(new IndexByteEncoder());\n\n let valueIdx = 0;\n for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {\n const value = values[valueIdx++];\n for (const encoder of encoders) {\n if (this.isInFilter(target, segment.fieldPath) && isArray(value)) {\n encoders = this.expandIndexValues(encoders, segment, value);\n } else {\n const directionalEncoder = encoder.forKind(segment.kind);\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n value,\n directionalEncoder\n );\n }\n }\n }\n return this.getEncodedBytes(encoders);\n }\n\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */\n private encodeBound(\n fieldIndex: FieldIndex,\n target: Target,\n bound: Bound\n ): Uint8Array[] {\n return this.encodeValues(fieldIndex, target, bound.position);\n }\n\n /** Returns the byte representation for the provided encoders. */\n private getEncodedBytes(encoders: IndexByteEncoder[]): Uint8Array[] {\n const result: Uint8Array[] = [];\n for (let i = 0; i < encoders.length; ++i) {\n result[i] = encoders[i].encodedBytes();\n }\n return result;\n }\n\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */\n private expandIndexValues(\n encoders: IndexByteEncoder[],\n segment: IndexSegment,\n value: ProtoValue\n ): IndexByteEncoder[] {\n const prefixes = [...encoders];\n const results: IndexByteEncoder[] = [];\n for (const arrayElement of value.arrayValue!.values || []) {\n for (const prefix of prefixes) {\n const clonedEncoder = new IndexByteEncoder();\n clonedEncoder.seed(prefix.encodedBytes());\n FirestoreIndexValueWriter.INSTANCE.writeIndexValue(\n arrayElement,\n clonedEncoder.forKind(segment.kind)\n );\n results.push(clonedEncoder);\n }\n }\n return results;\n }\n\n private isInFilter(target: Target, fieldPath: FieldPath): boolean {\n return !!target.filters.find(\n f =>\n f instanceof FieldFilter &&\n f.field.isEqual(fieldPath) &&\n (f.op === Operator.IN || f.op === Operator.NOT_IN)\n );\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise<FieldIndex[]> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n\n return (\n collectionGroup\n ? indexes.loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n : indexes.loadAll()\n ).next(indexConfigs => {\n const result: FieldIndex[] = [];\n return PersistencePromise.forEach(\n indexConfigs,\n (indexConfig: DbIndexConfiguration) => {\n return states\n .get([indexConfig.indexId!, this.uid])\n .next(indexState => {\n result.push(fromDbIndexConfiguration(indexConfig, indexState));\n });\n }\n ).next(() => result);\n });\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise<string | null> {\n return this.getFieldIndexes(transaction).next(indexes => {\n if (indexes.length === 0) {\n return null;\n }\n indexes.sort((l, r) => {\n const cmp = l.indexState.sequenceNumber - r.indexState.sequenceNumber;\n return cmp !== 0\n ? cmp\n : primitiveComparator(l.collectionGroup, r.collectionGroup);\n });\n return indexes[0].collectionGroup;\n });\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise<void> {\n const indexes = indexConfigurationStore(transaction);\n const states = indexStateStore(transaction);\n return this.getNextSequenceNumber(transaction).next(nextSequenceNumber =>\n indexes\n .loadAll(\n DbIndexConfigurationCollectionGroupIndex,\n IDBKeyRange.bound(collectionGroup, collectionGroup)\n )\n .next(configs =>\n PersistencePromise.forEach(configs, (config: DbIndexConfiguration) =>\n states.put(\n toDbIndexState(\n config.indexId!,\n this.uid,\n nextSequenceNumber,\n offset\n )\n )\n )\n )\n );\n }\n\n updateIndexEntries(\n transaction: PersistenceTransaction,\n documents: DocumentMap\n ): PersistencePromise<void> {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const memoizedIndexes = new Map<string, FieldIndex[]>();\n return PersistencePromise.forEach(documents, (key, doc) => {\n const memoizedCollectionIndexes = memoizedIndexes.get(\n key.collectionGroup\n );\n const fieldIndexes = memoizedCollectionIndexes\n ? PersistencePromise.resolve(memoizedCollectionIndexes)\n : this.getFieldIndexes(transaction, key.collectionGroup);\n\n return fieldIndexes.next(fieldIndexes => {\n memoizedIndexes.set(key.collectionGroup, fieldIndexes);\n return PersistencePromise.forEach(\n fieldIndexes,\n (fieldIndex: FieldIndex) => {\n return this.getExistingIndexEntries(\n transaction,\n key,\n fieldIndex\n ).next(existingEntries => {\n const newEntries = this.computeIndexEntries(doc, fieldIndex);\n if (!existingEntries.isEqual(newEntries)) {\n return this.updateEntries(\n transaction,\n doc,\n fieldIndex,\n existingEntries,\n newEntries\n );\n }\n return PersistencePromise.resolve();\n });\n }\n );\n });\n });\n }\n\n private addIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise<void> {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.put({\n indexId: indexEntry.indexId,\n uid: this.uid,\n arrayValue: indexEntry.arrayValue,\n directionalValue: indexEntry.directionalValue,\n orderedDocumentKey: this.encodeDirectionalKey(fieldIndex, document.key),\n documentKey: document.key.path.toArray()\n });\n }\n\n private deleteIndexEntry(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n indexEntry: IndexEntry\n ): PersistencePromise<void> {\n const indexEntries = indexEntriesStore(transaction);\n return indexEntries.delete([\n indexEntry.indexId,\n this.uid,\n indexEntry.arrayValue,\n indexEntry.directionalValue,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key.path.toArray()\n ]);\n }\n\n private getExistingIndexEntries(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n fieldIndex: FieldIndex\n ): PersistencePromise<SortedSet<IndexEntry>> {\n const indexEntries = indexEntriesStore(transaction);\n let results = new SortedSet<IndexEntry>(indexEntryComparator);\n return indexEntries\n .iterate(\n {\n index: DbIndexEntryDocumentKeyIndex,\n range: IDBKeyRange.only([\n fieldIndex.indexId,\n this.uid,\n this.encodeDirectionalKey(fieldIndex, documentKey)\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n entry.arrayValue,\n entry.directionalValue\n )\n );\n }\n )\n .next(() => results);\n }\n\n /** Creates the index entries for the given document. */\n private computeIndexEntries(\n document: Document,\n fieldIndex: FieldIndex\n ): SortedSet<IndexEntry> {\n let results = new SortedSet<IndexEntry>(indexEntryComparator);\n\n const directionalValue = this.encodeDirectionalElements(\n fieldIndex,\n document\n );\n if (directionalValue == null) {\n return results;\n }\n\n const arraySegment = fieldIndexGetArraySegment(fieldIndex);\n if (arraySegment != null) {\n const value = document.data.field(arraySegment.fieldPath);\n if (isArray(value)) {\n for (const arrayValue of value.arrayValue!.values || []) {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n this.encodeSingleElement(arrayValue),\n directionalValue\n )\n );\n }\n }\n } else {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n document.key,\n EMPTY_VALUE,\n directionalValue\n )\n );\n }\n\n return results;\n }\n\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */\n private updateEntries(\n transaction: PersistenceTransaction,\n document: Document,\n fieldIndex: FieldIndex,\n existingEntries: SortedSet<IndexEntry>,\n newEntries: SortedSet<IndexEntry>\n ): PersistencePromise<void> {\n logDebug(LOG_TAG, \"Updating index entries for document '%s'\", document.key);\n\n const promises: Array<PersistencePromise<void>> = [];\n diffSortedSets(\n existingEntries,\n newEntries,\n indexEntryComparator,\n /* onAdd= */ entry => {\n promises.push(\n this.addIndexEntry(transaction, document, fieldIndex, entry)\n );\n },\n /* onRemove= */ entry => {\n promises.push(\n this.deleteIndexEntry(transaction, document, fieldIndex, entry)\n );\n }\n );\n\n return PersistencePromise.waitFor(promises);\n }\n\n private getNextSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n let nextSequenceNumber = 1;\n const states = indexStateStore(transaction);\n return states\n .iterate(\n {\n index: DbIndexStateSequenceNumberIndex,\n reverse: true,\n range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])\n },\n (_, state, controller) => {\n controller.done();\n nextSequenceNumber = state.sequenceNumber + 1;\n }\n )\n .next(() => nextSequenceNumber);\n }\n\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */\n private createRange(\n lower: IndexEntry,\n upper: IndexEntry,\n notInValues: IndexEntry[]\n ): IDBKeyRange[] {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n notInValues = notInValues\n .sort((l, r) => indexEntryComparator(l, r))\n .filter(\n (el, i, values) => !i || indexEntryComparator(el, values[i - 1]) !== 0\n );\n\n const bounds: IndexEntry[] = [];\n bounds.push(lower);\n for (const notInValue of notInValues) {\n const cmpToLower = indexEntryComparator(notInValue, lower);\n const cmpToUpper = indexEntryComparator(notInValue, upper);\n\n if (cmpToLower === 0) {\n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n bounds[0] = lower.successor();\n } else if (cmpToLower > 0 && cmpToUpper < 0) {\n // `notInValue` is in the middle of the range\n bounds.push(notInValue);\n bounds.push(notInValue.successor());\n } else if (cmpToUpper > 0) {\n // `notInValue` (and all following values) are out of the range\n break;\n }\n }\n bounds.push(upper);\n\n const ranges: IDBKeyRange[] = [];\n for (let i = 0; i < bounds.length; i += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.isRangeMatchable(bounds[i], bounds[i + 1])) {\n return [];\n }\n\n const lowerBound = [\n bounds[i].indexId,\n this.uid,\n bounds[i].arrayValue,\n bounds[i].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n const upperBound = [\n bounds[i + 1].indexId,\n this.uid,\n bounds[i + 1].arrayValue,\n bounds[i + 1].directionalValue,\n EMPTY_VALUE,\n []\n ] as DbIndexEntryKey;\n\n ranges.push(IDBKeyRange.bound(lowerBound, upperBound));\n }\n return ranges;\n }\n\n isRangeMatchable(lowerBound: IndexEntry, upperBound: IndexEntry): boolean {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return indexEntryComparator(lowerBound, upperBound) > 0;\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise<IndexOffset> {\n return this.getFieldIndexes(transaction, collectionGroup).next(\n getMinOffsetFromFieldIndexes\n );\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<IndexOffset> {\n return PersistencePromise.mapArray(\n this.getSubTargets(target),\n (subTarget: Target) =>\n this.getFieldIndex(transaction, subTarget).next(index =>\n index ? index : fail('Target cannot be served from index')\n )\n ).next(getMinOffsetFromFieldIndexes);\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 getStore<DbCollectionParentKey, DbCollectionParent>(\n txn,\n DbCollectionParentStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */\nfunction indexEntriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexEntryKey, DbIndexEntry> {\n return getStore<DbIndexEntryKey, DbIndexEntry>(txn, DbIndexEntryStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */\nfunction indexConfigurationStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexConfigurationKey, DbIndexConfiguration> {\n return getStore<DbIndexConfigurationKey, DbIndexConfiguration>(\n txn,\n DbIndexConfigurationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */\nfunction indexStateStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbIndexStateKey, DbIndexState> {\n return getStore<DbIndexStateKey, DbIndexState>(txn, DbIndexStateStore);\n}\n\nfunction getMinOffsetFromFieldIndexes(fieldIndexes: FieldIndex[]): IndexOffset {\n hardAssert(\n fieldIndexes.length !== 0,\n 'Found empty index group when looking for least recent index offset.'\n );\n\n let minOffset: IndexOffset = fieldIndexes[0].indexState.offset;\n let maxBatchId: number = minOffset.largestBatchId;\n for (let i = 1; i < fieldIndexes.length; i++) {\n const newOffset: IndexOffset = fieldIndexes[i].indexState.offset;\n if (indexOffsetComparator(newOffset, minOffset) < 0) {\n minOffset = newOffset;\n }\n if (maxBatchId < newOffset.largestBatchId) {\n maxBatchId = newOffset.largestBatchId;\n }\n }\n return new IndexOffset(minOffset.readTime, minOffset.documentKey, maxBatchId);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\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\nexport const GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport const LRU_COLLECTION_DISABLED = -1;\nexport const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n\nexport class LruParams {\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 LRU_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 LRU_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\nexport interface LruGarbageCollector {\n readonly params: LruParams;\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults>;\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\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<number>;\n\n /**\n * Removes documents that have a sequence number equal to or less than the\n * upper bound and are not otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n\n /**\n * Removes targets with a sequence number equal to or less than the given\n * upper bound, and removes document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\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\n/**\n * Persistence layers intending to use LRU Garbage collection should have\n * reference delegates that implement this interface. This interface defines the\n * operations that the LRU garbage collector 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\n * `upperBound`, and are not present in the `activeTargetIds` set.\n *\n * @returns 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\n * number less than or equal to the given `upperBound`.\n *\n * @returns 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 * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { fail, hardAssert } from '../util/assert';\n\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbRemoteDocument\n} from './indexeddb_schema';\nimport { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n newDbDocumentMutationKey\n} from './indexeddb_sentinels';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: { batchId: number; mutations: Array<{ key: DocumentKey }> }\n): PersistencePromise<DocumentKey[]> {\n const mutationStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatchStore\n );\n const indexTxn = txn.store<DbDocumentMutationKey, DbDocumentMutation>(\n DbDocumentMutationStore\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 hardAssert(\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 = newDbDocumentMutationKey(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Returns an approximate size for the given document.\n */\nexport function dbDocumentSize(\n doc: DbRemoteDocument | DbRemoteDocumentLegacy | null\n): number {\n if (!doc) {\n return 0;\n }\n\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail('Unknown remote document type');\n }\n return JSON.stringify(value).length;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { isCollectionGroupQuery, isDocumentQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { decodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { removeMutationBatch } from './indexeddb_mutation_batch_impl';\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue\n} from './indexeddb_schema';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationPlaceholder,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationQueueKey,\n DbMutationQueueStore,\n newDbDocumentMutationKey,\n newDbDocumentMutationPrefixForPath,\n newDbDocumentMutationPrefixForUser\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction, getStore } from './indexeddb_transaction';\nimport {\n fromDbMutationBatch,\n LocalSerializer,\n toDbMutationBatch\n} from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } 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 hardAssert(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: DbMutationBatchUserMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\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 hardAssert(\n typeof batchId === 'number',\n 'Auto-generated key is not a number'\n );\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = toDbMutationBatch(this.serializer, 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 = newDbDocumentMutationKey(\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, DbDocumentMutationPlaceholder)\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 hardAssert(\n dbBatch.userId === this.userId,\n `Unexpected user '${dbBatch.userId}' for mutation batch ${batchId}`\n );\n return fromDbMutationBatch(this.serializer, dbBatch);\n }\n return null;\n });\n }\n\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n 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: DbMutationBatchUserMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n hardAssert(\n dbBatch.batchId >= nextBatchId,\n 'Should have found mutation after ' + nextBatchId\n );\n foundBatch = fromDbMutationBatch(this.serializer, 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: DbMutationBatchUserMutationsIndex, 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(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, 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 = newDbDocumentMutationPrefixForPath(\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 = decodeResourcePath(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 hardAssert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(fromDbMutationBatch(this.serializer, 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 = newDbDocumentMutationPrefixForPath(\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 = decodeResourcePath(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 debugAssert(\n !isDocumentQuery(query),\n \"Document queries shouldn't go down this path\"\n );\n debugAssert(\n !isCollectionGroupQuery(query),\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 = newDbDocumentMutationPrefixForPath(\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 = decodeResourcePath(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 hardAssert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(fromDbMutationBatch(this.serializer, 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.markPotentiallyOrphaned(\n transaction,\n key\n );\n }\n );\n });\n }\n\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n 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 newDbDocumentMutationPrefixForUser(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 = decodeResourcePath(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n hardAssert(\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 userId: this.userId,\n lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n lastStreamToken: ''\n }\n );\n });\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise<boolean> {\n const indexKey = newDbDocumentMutationPrefixForPath(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 * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbMutationBatchKey, DbMutationBatch> {\n return getStore<DbMutationBatchKey, DbMutationBatch>(\n txn,\n DbMutationBatchStore\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 getStore<DbDocumentMutationKey, DbDocumentMutation>(\n txn,\n DbDocumentMutationStore\n );\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 getStore<DbMutationQueueKey, DbMutationQueue>(\n txn,\n DbMutationQueueStore\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\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 target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentKey,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetQueryTargetsIndexName,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\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 allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise<TargetId> {\n return this.retrieveMetadata(transaction).next(metadata => {\n const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n metadata.highestTargetId = targetIdGenerator.next();\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 this.retrieveMetadata(transaction).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\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 =\n 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 hardAssert(\n metadata.targetCount > 0,\n 'Removing from an empty target cache'\n );\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 = 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 = fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise<DbTargetGlobal> {\n return globalTargetStore(transaction)\n .get(DbTargetGlobalKey)\n .next(metadata => {\n hardAssert(metadata !== null, 'Missing metadata row.');\n return metadata;\n });\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise<void> {\n return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return targetsStore(transaction).put(\n toDbTarget(this.serializer, 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 = canonifyTarget(target);\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: DbTargetQueryTargetsIndexName },\n (key, value, control) => {\n const found = fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (targetEquals(target, 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 = encodeResourcePath(key.path);\n promises.push(store.put({ targetId, path }));\n promises.push(this.referenceDelegate.addReference(txn, targetId, 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 = encodeResourcePath(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, targetId, 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 = decodeResourcePath(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 = encodeResourcePath(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: DbTargetDocumentDocumentTargetsIndex,\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 /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n 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 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 getStore<DbTargetKey, DbTarget>(txn, DbTargetStore);\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 getStore<DbTargetGlobalKey, DbTargetGlobal>(txn, DbTargetGlobalStore);\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 getStore<DbTargetDocumentKey, DbTargetDocument>(\n txn,\n DbTargetDocumentStore\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\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// 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];\n\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 * 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 implements Scheduler {\n private gcTask: DelayedOperation<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 debugAssert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LRU_COLLECTION_DISABLED\n ) {\n this.scheduleGC(INITIAL_GC_DELAY_MS);\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(delay: number): void {\n debugAssert(\n this.gcTask === null,\n 'Cannot schedule GC while a task is pending'\n );\n logDebug(LOG_TAG, `Garbage collection scheduled in ${delay}ms`);\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n async () => {\n this.gcTask = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during garbage collection: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.scheduleGC(REGULAR_GC_DELAY_MS);\n }\n );\n }\n}\n\n/**\n * Implements the steps for LRU garbage collection.\n */\nclass LruGarbageCollectorImpl implements LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\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 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 removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\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 (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) {\n logDebug('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 logDebug(\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 logDebug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect =\n this.params.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 (getLogLevel() <= 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 logDebug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve<LruResults>({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n\nexport function newLruGarbageCollector(\n delegate: LruDelegate,\n params: LruParams\n): LruGarbageCollector {\n return new LruGarbageCollectorImpl(delegate, params);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n decodeResourcePath,\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n documentTargetStore,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n ActiveTargets,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: Persistence, params: LruParams) {\n this.garbageCollector = newLruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n const docCountPromise = this.orphanedDocumentCount(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 orphanedDocumentCount(\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 addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\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.getTargetCache() as IndexedDbTargetCache).removeTargets(\n txn,\n upperBound,\n activeTargetIds\n );\n }\n\n markPotentiallyOrphaned(\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 return mutationQueuesContainKey(txn, docKey);\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, SnapshotVersion.min());\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: DbTargetDocumentDocumentTargetsIndex\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(decodeResourcePath(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(decodeResourcePath(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, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns 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 { targetId: 0, path: encodeResourcePath(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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\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.\n protected changes: ObjectMap<DocumentKey, MutableDocument> = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n private changesApplied = false;\n\n protected abstract getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument>;\n\n protected abstract getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap>;\n\n protected abstract applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void>;\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(document: MutableDocument): void {\n this.assertNotApplied();\n this.changes.set(document.key, document);\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 this.changes.set(\n key,\n MutableDocument.newInvalidDocument(key).setReadTime(readTime)\n );\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 * @returns The cached document or an invalid document if we have nothing\n * cached.\n */\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutableDocument> {\n this.assertNotApplied();\n const bufferedEntry = this.changes.get(documentKey);\n if (bufferedEntry !== undefined) {\n return PersistencePromise.resolve(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 * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\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 debugAssert(!this.changesApplied, 'Changes have already been applied.');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentSizeEntries,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentStore,\n DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbRemoteDocument,\n LocalSerializer,\n toDbRemoteDocument,\n toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n document: MutableDocument;\n size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n indexManager!: IndexManager;\n\n constructor(readonly serializer: LocalSerializer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.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 addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise<void> {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(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 removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n ): PersistencePromise<void> {\n const store = remoteDocumentsStore(transaction);\n return store.delete(dbReadTimeKey(documentKey, readTime));\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 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<MutableDocument> {\n let doc = MutableDocument.newInvalidDocument(documentKey);\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n }\n )\n .next(() => doc);\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<DocumentSizeEntry> {\n let result = {\n size: 0,\n document: MutableDocument.newInvalidDocument(documentKey)\n };\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n result = {\n document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n };\n }\n )\n .next(() => result);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n let results = mutableDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, 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 * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<DocumentSizeEntries> {\n let results = mutableDocumentMap();\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(key, dbRemoteDoc);\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n }\n ).next(() => {\n return { documents: 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 let sortedKeys = new SortedSet<DocumentKey>(dbKeyComparator);\n documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n const range = IDBKeyRange.bound(\n dbKey(sortedKeys.first()!),\n dbKey(sortedKeys.last()!)\n );\n const keyIter = sortedKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate(\n { index: DbRemoteDocumentDocumentKeyIndex, range },\n (_, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments([\n ...dbRemoteDoc.prefixPath,\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n ]);\n\n // Go through keys not found in cache.\n while (nextKey && dbKeyComparator(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(dbKey(nextKey));\n } else {\n control.done();\n }\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 offset: IndexOffset,\n mutatedDocs: OverlayMap,\n context?: QueryContext\n ): PersistencePromise<MutableDocumentMap> {\n const collection = query.path;\n const startKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n toDbTimestampKey(offset.readTime),\n offset.documentKey.path.isEmpty()\n ? ''\n : offset.documentKey.path.lastSegment()\n ];\n const endKey: DbRemoteDocumentKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n ''\n ];\n\n return remoteDocumentsStore(transaction)\n .loadAll(IDBKeyRange.bound(startKey, endKey, true))\n .next(dbRemoteDocs => {\n context?.incrementDocumentReadCount(dbRemoteDocs.length);\n let results = mutableDocumentMap();\n for (const dbRemoteDoc of dbRemoteDocs) {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n if (\n document.isFoundDocument() &&\n (queryMatches(query, document) || mutatedDocs.has(document.key))\n ) {\n // Either the document matches the given query, or it is mutated.\n results = results.insert(document.key, document);\n }\n }\n return results;\n });\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limit: number\n ): PersistencePromise<MutableDocumentMap> {\n debugAssert(limit > 0, 'Limit should be at least 1');\n let results = mutableDocumentMap();\n\n const startKey = dbCollectionGroupKey(collectionGroup, offset);\n const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentCollectionGroupIndex,\n range: IDBKeyRange.bound(startKey, endKey, true)\n },\n (_, dbRemoteDoc, control) => {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n results = results.insert(document.key, document);\n if (results.size === limit) {\n control.done();\n }\n }\n )\n .next(() => results);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentChangeBuffer(\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(DbRemoteDocumentGlobalKey)\n .next(metadata => {\n hardAssert(!!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(DbRemoteDocumentGlobalKey, metadata);\n }\n\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n documentKey: DocumentKey,\n dbRemoteDoc: DbRemoteDocument | null\n ): MutableDocument {\n if (dbRemoteDoc) {\n const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n const isSentinelRemoval =\n doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n if (!isSentinelRemoval) {\n return doc;\n }\n }\n return MutableDocument.newInvalidDocument(documentKey);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n return new IndexedDbRemoteDocumentCacheImpl(serializer);\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 */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n protected documentStates: ObjectMap<\n DocumentKey,\n { size: number; readTime: SnapshotVersion }\n > = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\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: IndexedDbRemoteDocumentCacheImpl,\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, documentChange) => {\n const previousDoc = this.documentStates.get(key);\n debugAssert(\n previousDoc !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n promises.push(\n this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n );\n if (documentChange.isValidDocument()) {\n debugAssert(\n !documentChange.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n const doc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousDoc.size;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousDoc.size;\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 = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange.convertToNoDocument(SnapshotVersion.min())\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\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<MutableDocument> {\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 this.documentStates.set(documentKey, {\n size: getResult.size,\n readTime: getResult.document.readTime\n });\n return getResult.document;\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\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(({ documents, 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 // `MutableDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentStates.set(documentKey, {\n size,\n readTime: documents.get(documentKey)!.readTime\n });\n });\n return documents;\n });\n }\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal> {\n return getStore<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal>(\n txn,\n DbRemoteDocumentGlobalStore\n );\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 getStore<DbRemoteDocumentKey, DbRemoteDocument>(\n txn,\n DbRemoteDocumentStore\n );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n toDbTimestampKey(readTime),\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n collectionGroup: string,\n offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n const path = offset.documentKey.path.toArray();\n return [\n /* collection id */ collectionGroup,\n toDbTimestampKey(offset.readTime),\n /* prefix path */ path.slice(0, path.length - 2),\n /* document id */ path.length > 0 ? path[path.length - 1] : ''\n ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n const left = l.path.toArray();\n const right = r.path.toArray();\n\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let cmp = 0;\n for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n cmp = primitiveComparator(left[i], right[i]);\n if (cmp) {\n return cmp;\n }\n }\n\n cmp = primitiveComparator(left.length, right.length);\n if (cmp) {\n return cmp;\n }\n\n cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n if (cmp) {\n return cmp;\n }\n\n return primitiveComparator(left[left.length - 1], right[right.length - 1]);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { FieldMask } from '../model/field_mask';\n\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nexport class OverlayedDocument {\n constructor(\n readonly overlayedDocument: Document,\n\n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n readonly mutatedFields: FieldMask | null\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n asCollectionQueryAtPath,\n isCollectionGroupQuery,\n isDocumentQuery,\n Query,\n queryMatches\n} from '../core/query';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n DocumentKeySet,\n OverlayMap,\n DocumentMap,\n MutableDocumentMap,\n newDocumentKeyMap,\n newMutationMap,\n newOverlayMap,\n documentMap,\n mutableDocumentMap,\n documentKeySet,\n DocumentKeyMap,\n convertOverlayedDocumentMapToDocumentMap,\n OverlayedDocumentMap,\n newOverlayedDocumentMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset, INITIAL_LARGEST_BATCH_ID } from '../model/field_index';\nimport { FieldMask } from '../model/field_mask';\nimport {\n calculateOverlayMutation,\n mutationApplyToLocalView,\n PatchMutation\n} from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\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 documentOverlayCache: DocumentOverlayCache,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<Document> {\n let overlay: Overlay | null = null;\n return this.documentOverlayCache\n .getOverlay(transaction, key)\n .next(value => {\n overlay = value;\n return this.remoteDocumentCache.getEntry(transaction, key);\n })\n .next(document => {\n if (overlay !== null) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n return document as Document;\n });\n }\n\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */\n getDocuments(\n transaction: PersistenceTransaction,\n keys: DocumentKeySet\n ): PersistencePromise<DocumentMap> {\n return this.remoteDocumentCache\n .getEntries(transaction, keys)\n .next(docs =>\n this.getLocalViewOfDocuments(transaction, docs, documentKeySet()).next(\n () => docs as DocumentMap\n )\n );\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 * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */\n getLocalViewOfDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n existenceStateChanged: DocumentKeySet = documentKeySet()\n ): PersistencePromise<DocumentMap> {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() => {\n return this.computeViews(\n transaction,\n docs,\n overlays,\n existenceStateChanged\n ).next(computeViewsResult => {\n let result = documentMap();\n computeViewsResult.forEach((documentKey, overlayedDocument) => {\n result = result.insert(\n documentKey,\n overlayedDocument.overlayedDocument\n );\n });\n return result;\n });\n });\n }\n\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */\n getOverlayedDocuments(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise<OverlayedDocumentMap> {\n const overlays = newOverlayMap();\n return this.populateOverlays(transaction, overlays, docs).next(() =>\n this.computeViews(transaction, docs, overlays, documentKeySet())\n );\n }\n\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */\n private populateOverlays(\n transaction: PersistenceTransaction,\n overlays: OverlayMap,\n docs: MutableDocumentMap\n ): PersistencePromise<void> {\n const missingOverlays: DocumentKey[] = [];\n docs.forEach(key => {\n if (!overlays.has(key)) {\n missingOverlays.push(key);\n }\n });\n return this.documentOverlayCache\n .getOverlays(transaction, missingOverlays)\n .next(result => {\n result.forEach((key, val) => {\n overlays.set(key, val);\n });\n });\n }\n\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */\n computeViews(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap,\n overlays: OverlayMap,\n existenceStateChanged: DocumentKeySet\n ): PersistencePromise<OverlayedDocumentMap> {\n let recalculateDocuments = mutableDocumentMap();\n const mutatedFields = newDocumentKeyMap<FieldMask | null>();\n const results = newOverlayedDocumentMap();\n docs.forEach((_, doc) => {\n const overlay = overlays.get(doc.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n if (\n existenceStateChanged.has(doc.key) &&\n (overlay === undefined || overlay.mutation instanceof PatchMutation)\n ) {\n recalculateDocuments = recalculateDocuments.insert(doc.key, doc);\n } else if (overlay !== undefined) {\n mutatedFields.set(doc.key, overlay.mutation.getFieldMask());\n mutationApplyToLocalView(\n overlay.mutation,\n doc,\n overlay.mutation.getFieldMask(),\n Timestamp.now()\n );\n } else {\n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n mutatedFields.set(doc.key, FieldMask.empty());\n }\n });\n\n return this.recalculateAndSaveOverlays(\n transaction,\n recalculateDocuments\n ).next(recalculatedFields => {\n recalculatedFields.forEach((documentKey, mask) =>\n mutatedFields.set(documentKey, mask)\n );\n docs.forEach((documentKey, document) =>\n results.set(\n documentKey,\n new OverlayedDocument(\n document,\n mutatedFields.get(documentKey) ?? null\n )\n )\n );\n return results;\n });\n }\n\n private recalculateAndSaveOverlays(\n transaction: PersistenceTransaction,\n docs: MutableDocumentMap\n ): PersistencePromise<DocumentKeyMap<FieldMask | null>> {\n const masks = newDocumentKeyMap<FieldMask | null>();\n // A reverse lookup map from batch id to the documents within that batch.\n let documentsByBatchId = new SortedMap<number, DocumentKeySet>(\n (key1: number, key2: number) => key1 - key2\n );\n let processed = documentKeySet();\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKeys(transaction, docs)\n .next(batches => {\n for (const batch of batches) {\n batch.keys().forEach(key => {\n const baseDoc = docs.get(key);\n if (baseDoc === null) {\n return;\n }\n let mask: FieldMask | null = masks.get(key) || FieldMask.empty();\n mask = batch.applyToLocalView(baseDoc, mask);\n masks.set(key, mask);\n const newSet = (\n documentsByBatchId.get(batch.batchId) || documentKeySet()\n ).add(key);\n documentsByBatchId = documentsByBatchId.insert(\n batch.batchId,\n newSet\n );\n });\n }\n })\n .next(() => {\n const promises: Array<PersistencePromise<void>> = [];\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n const iter = documentsByBatchId.getReverseIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const batchId = entry.key;\n const keys = entry.value;\n const overlays = newMutationMap();\n keys.forEach(key => {\n if (!processed.has(key)) {\n const overlayMutation = calculateOverlayMutation(\n docs.get(key)!,\n masks.get(key)!\n );\n if (overlayMutation !== null) {\n overlays.set(key, overlayMutation);\n }\n processed = processed.add(key);\n }\n });\n promises.push(\n this.documentOverlayCache.saveOverlays(\n transaction,\n batchId,\n overlays\n )\n );\n }\n return PersistencePromise.waitFor(promises);\n })\n .next(() => masks);\n }\n\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */\n recalculateAndSaveOverlaysForDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<DocumentKeyMap<FieldMask | null>> {\n return this.remoteDocumentCache\n .getEntries(transaction, documentKeys)\n .next(docs => this.recalculateAndSaveOverlays(transaction, docs));\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 offset - Read time and key to start scanning by (exclusive).\n * @param context - A optional tracker to keep a record of important details\n * during database local query execution.\n */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n if (isDocumentQuery(query)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n } else if (isCollectionGroupQuery(query)) {\n return this.getDocumentsMatchingCollectionGroupQuery(\n transaction,\n query,\n offset,\n context\n );\n } else {\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n query,\n offset,\n context\n );\n }\n }\n\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n * <p>The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */\n getNextDocuments(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n count: number\n ): PersistencePromise<LocalWriteResult> {\n return this.remoteDocumentCache\n .getAllFromCollectionGroup(transaction, collectionGroup, offset, count)\n .next((originalDocs: MutableDocumentMap) => {\n const overlaysPromise: PersistencePromise<OverlayMap> =\n count - originalDocs.size > 0\n ? this.documentOverlayCache.getOverlaysForCollectionGroup(\n transaction,\n collectionGroup,\n offset.largestBatchId,\n count - originalDocs.size\n )\n : PersistencePromise.resolve(newOverlayMap());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let largestBatchId = INITIAL_LARGEST_BATCH_ID;\n let modifiedDocs = originalDocs;\n return overlaysPromise.next(overlays => {\n return PersistencePromise.forEach(\n overlays,\n (key: DocumentKey, overlay: Overlay) => {\n if (largestBatchId < overlay.largestBatchId) {\n largestBatchId = overlay.largestBatchId;\n }\n if (originalDocs.get(key)) {\n return PersistencePromise.resolve();\n }\n return this.remoteDocumentCache\n .getEntry(transaction, key)\n .next(doc => {\n modifiedDocs = modifiedDocs.insert(key, doc);\n });\n }\n )\n .next(() =>\n this.populateOverlays(transaction, overlays, originalDocs)\n )\n .next(() =>\n this.computeViews(\n transaction,\n modifiedDocs,\n overlays,\n documentKeySet()\n )\n )\n .next(localDocs => ({\n batchId: largestBatchId,\n changes: convertOverlayedDocumentMapToDocumentMap(localDocs)\n }));\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 document => {\n let result = documentMap();\n if (document.isFoundDocument()) {\n result = result.insert(document.key, document);\n }\n return result;\n }\n );\n }\n\n private getDocumentsMatchingCollectionGroupQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n debugAssert(\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 = asCollectionQueryAtPath(\n query,\n parent.child(collectionId)\n );\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n collectionQuery,\n offset,\n context\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 offset: IndexOffset,\n context?: QueryContext\n ): PersistencePromise<DocumentMap> {\n // Query the remote documents and overlay mutations.\n let overlays: OverlayMap;\n return this.documentOverlayCache\n .getOverlaysForCollection(transaction, query.path, offset.largestBatchId)\n .next(result => {\n overlays = result;\n return this.remoteDocumentCache.getDocumentsMatchingQuery(\n transaction,\n query,\n offset,\n overlays,\n context\n );\n })\n .next(remoteDocuments => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n overlays.forEach((_, overlay) => {\n const key = overlay.getKey();\n if (remoteDocuments.get(key) === null) {\n remoteDocuments = remoteDocuments.insert(\n key,\n MutableDocument.newInvalidDocument(key)\n );\n }\n });\n\n // Apply the overlays and match against the query.\n let results = documentMap();\n remoteDocuments.forEach((key, document) => {\n const overlay = overlays.get(key);\n if (overlay !== undefined) {\n mutationApplyToLocalView(\n overlay.mutation,\n document,\n FieldMask.empty(),\n Timestamp.now()\n );\n }\n // Finally, insert the documents that still match the query\n if (queryMatches(query, document)) {\n results = results.insert(key, document);\n }\n });\n return results;\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n NamedQuery as ProtoNamedQuery,\n BundleMetadata as ProtoBundleMetadata\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport {\n fromBundleMetadata,\n fromProtoNamedQuery,\n LocalSerializer\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\nexport class MemoryBundleCache implements BundleCache {\n private bundles = new Map<string, BundleMetadata>();\n private namedQueries = new Map<string, NamedQuery>();\n\n constructor(private serializer: LocalSerializer) {}\n\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise<BundleMetadata | undefined> {\n return PersistencePromise.resolve(this.bundles.get(bundleId));\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise<void> {\n this.bundles.set(bundleMetadata.id!, fromBundleMetadata(bundleMetadata));\n return PersistencePromise.resolve();\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise<NamedQuery | undefined> {\n return PersistencePromise.resolve(this.namedQueries.get(queryName));\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise<void> {\n this.namedQueries.set(query.name!, fromProtoNamedQuery(query));\n return PersistencePromise.resolve();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n documentKeySet,\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */\nexport class MemoryDocumentOverlayCache implements DocumentOverlayCache {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n private overlays = new SortedMap<DocumentKey, Overlay>(\n DocumentKey.comparator\n );\n private overlayByBatchId = new Map<number, DocumentKeySet>();\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<Overlay | null> {\n return PersistencePromise.resolve(this.overlays.get(key));\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n return this.getOverlay(transaction, key).next(overlay => {\n if (overlay !== null) {\n result.set(key, overlay);\n }\n });\n }).next(() => result);\n }\n\n saveOverlays(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n overlays: MutationMap\n ): PersistencePromise<void> {\n overlays.forEach((_, mutation) => {\n this.saveOverlay(transaction, largestBatchId, mutation);\n });\n return PersistencePromise.resolve();\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise<void> {\n const keys = this.overlayByBatchId.get(batchId);\n if (keys !== undefined) {\n keys.forEach(key => (this.overlays = this.overlays.remove(key)));\n this.overlayByBatchId.delete(batchId);\n }\n return PersistencePromise.resolve();\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise<OverlayMap> {\n const result = newOverlayMap();\n\n const immediateChildrenPathLength = collection.length + 1;\n const prefix = new DocumentKey(collection.child(''));\n const iter = this.overlays.getIteratorFrom(prefix);\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (!collection.isPrefixOf(key.path)) {\n break;\n }\n // Documents from sub-collections\n if (key.path.length !== immediateChildrenPathLength) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n result.set(overlay.getKey(), overlay);\n }\n }\n\n return PersistencePromise.resolve(result);\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise<OverlayMap> {\n let batchIdToOverlays = new SortedMap<number, OverlayMap>(\n (key1: number, key2: number) => key1 - key2\n );\n\n const iter = this.overlays.getIterator();\n while (iter.hasNext()) {\n const entry = iter.getNext();\n const overlay = entry.value;\n const key = overlay.getKey();\n if (key.getCollectionGroup() !== collectionGroup) {\n continue;\n }\n if (overlay.largestBatchId > sinceBatchId) {\n let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId);\n if (overlaysForBatchId === null) {\n overlaysForBatchId = newOverlayMap();\n batchIdToOverlays = batchIdToOverlays.insert(\n overlay.largestBatchId,\n overlaysForBatchId\n );\n }\n overlaysForBatchId.set(overlay.getKey(), overlay);\n }\n }\n\n const result = newOverlayMap();\n const batchIter = batchIdToOverlays.getIterator();\n while (batchIter.hasNext()) {\n const entry = batchIter.getNext();\n const overlays = entry.value;\n overlays.forEach((key, overlay) => result.set(key, overlay));\n if (result.size() >= count) {\n break;\n }\n }\n return PersistencePromise.resolve(result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n largestBatchId: number,\n mutation: Mutation\n ): void {\n // Remove the association of the overlay to its batch id.\n const existing = this.overlays.get(mutation.key);\n if (existing !== null) {\n const newSet = this.overlayByBatchId\n .get(existing.largestBatchId)!\n .delete(mutation.key);\n this.overlayByBatchId.set(existing.largestBatchId, newSet);\n }\n\n this.overlays = this.overlays.insert(\n mutation.key,\n new Overlay(largestBatchId, mutation)\n );\n\n // Create the association of this overlay to the given largestBatchId.\n let batch = this.overlayByBatchId.get(largestBatchId);\n if (batch === undefined) {\n batch = documentKeySet();\n this.overlayByBatchId.set(largestBatchId, batch);\n }\n this.overlayByBatchId.set(largestBatchId, batch.add(mutation.key));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, TargetId } from '../core/types';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\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 = new DocumentKey(new ResourcePath([]));\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 = new DocumentKey(new ResourcePath([]));\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCollectionGroupQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\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 /** 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 addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise<MutationBatch> {\n debugAssert(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 debugAssert(\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 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 debugAssert(\n documentKey.isEqual(ref.key),\n \"Should only iterate over a single key's batches\"\n );\n const batch = this.findMutationBatch(ref.targetOrBatchId);\n debugAssert(\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 debugAssert(\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 debugAssert(\n !isCollectionGroupQuery(query),\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.\n const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n hardAssert(\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.markPotentiallyOrphaned(\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 debugAssert(\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 debugAssert(\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 * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */\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 debugAssert(batch.batchId === batchId, 'If found batch must match');\n return batch;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert, fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { IndexManager } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\n\nexport type DocumentSizer = (doc: Document) => number;\n\n/** Miscellaneous collection types / constants. */\ninterface MemoryRemoteDocumentCacheEntry {\n document: Document;\n size: number;\n}\n\ntype DocumentEntryMap = SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>;\nfunction documentEntryMap(): DocumentEntryMap {\n return new SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>(\n DocumentKey.comparator\n );\n}\n\nexport interface MemoryRemoteDocumentCache extends RemoteDocumentCache {\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise<void>\n ): PersistencePromise<void>;\n}\n\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass MemoryRemoteDocumentCacheImpl implements MemoryRemoteDocumentCache {\n /** Underlying cache of documents and their read times. */\n private docs = documentEntryMap();\n private indexManager!: IndexManager;\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\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(private readonly sizer: DocumentSizer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\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 addEntry(\n transaction: PersistenceTransaction,\n doc: MutableDocument\n ): PersistencePromise<void> {\n debugAssert(\n !doc.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 document: doc.mutableCopy(),\n size: currentSize\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 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<MutableDocument> {\n const entry = this.docs.get(documentKey);\n return PersistencePromise.resolve(\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n let results = mutableDocumentMap();\n documentKeys.forEach(documentKey => {\n const entry = this.docs.get(documentKey);\n results = results.insert(\n documentKey,\n entry\n ? entry.document.mutableCopy()\n : MutableDocument.newInvalidDocument(documentKey)\n );\n });\n return PersistencePromise.resolve(results);\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap\n ): PersistencePromise<MutableDocumentMap> {\n let results = mutableDocumentMap();\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 collectionPath = query.path;\n const prefix = new DocumentKey(collectionPath.child(''));\n const iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n const {\n key,\n value: { document }\n } = iterator.getNext();\n if (!collectionPath.isPrefixOf(key.path)) {\n break;\n }\n if (key.path.length > collectionPath.length + 1) {\n // Exclude entries from subcollections.\n continue;\n }\n if (\n indexOffsetComparator(newIndexOffsetFromDocument(document), offset) <= 0\n ) {\n // The document sorts before the offset.\n continue;\n }\n if (!mutatedDocs.has(document.key) && !queryMatches(query, document)) {\n // The document cannot possibly match the query.\n continue;\n }\n\n results = results.insert(document.key, document.mutableCopy());\n }\n return PersistencePromise.resolve(results);\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limti: number\n ): PersistencePromise<MutableDocumentMap> {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n fail('getAllFromCollectionGroup() is not supported.');\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 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 MemoryRemoteDocumentChangeBuffer(this);\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return PersistencePromise.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\nexport function newMemoryRemoteDocumentCache(\n sizer: DocumentSizer\n): MemoryRemoteDocumentCache {\n return new MemoryRemoteDocumentCacheImpl(sizer);\n}\n\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n constructor(private readonly documentCache: MemoryRemoteDocumentCacheImpl) {\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.isValidDocument()) {\n promises.push(this.documentCache.addEntry(transaction, doc));\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<MutableDocument> {\n return this.documentCache.getEntry(transaction, documentKey);\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<MutableDocumentMap> {\n return this.documentCache.getEntries(transaction, documentKeys);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\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 { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\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>(\n t => canonifyTarget(t),\n targetEquals\n );\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: Persistence) {}\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 this.highestTargetId = this.targetIdGenerator.next();\n return PersistencePromise.resolve(this.highestTargetId);\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.targetIdGenerator = new TargetIdGenerator(targetId);\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 debugAssert(\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 debugAssert(\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 debugAssert(this.targetCount > 0, 'Removing a target from an empty cache');\n debugAssert(\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 addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.addReferences(keys, targetId);\n return PersistencePromise.resolve();\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.markPotentiallyOrphaned(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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { estimateByteSize } from '../model/values';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { fail } from '../util/assert';\nimport { logDebug } from '../util/log';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { LocalSerializer } from './local_serializer';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { MemoryBundleCache } from './memory_bundle_cache';\nimport { MemoryDocumentOverlayCache } from './memory_document_overlay_cache';\nimport { MemoryIndexManager } from './memory_index_manager';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport {\n MemoryRemoteDocumentCache,\n newMemoryRemoteDocumentCache\n} from './memory_remote_document_cache';\nimport { MemoryTargetCache } from './memory_target_cache';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode\n} from './persistence_transaction';\nimport { ReferenceSet } from './reference_set';\nimport { TargetData } from './target_data';\n\nconst LOG_TAG = 'MemoryPersistence';\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 overlays: { [user: string]: MemoryDocumentOverlayCache } = {};\n private readonly remoteDocumentCache: MemoryRemoteDocumentCache;\n private readonly targetCache: MemoryTargetCache;\n private readonly bundleCache: MemoryBundleCache;\n private readonly listenSequence = new ListenSequence(0);\n private serializer: LocalSerializer;\n\n private _started = false;\n\n readonly referenceDelegate: MemoryReferenceDelegate;\n\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(\n referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate,\n serializer: JsonProtoSerializer\n ) {\n this._started = true;\n this.referenceDelegate = referenceDelegateFactory(this);\n this.targetCache = new MemoryTargetCache(this);\n const sizer = (doc: Document): number =>\n this.referenceDelegate.documentSize(doc);\n this.indexManager = new MemoryIndexManager();\n this.remoteDocumentCache = newMemoryRemoteDocumentCache(sizer);\n this.serializer = new LocalSerializer(serializer);\n this.bundleCache = new MemoryBundleCache(this.serializer);\n }\n\n start(): Promise<void> {\n return Promise.resolve();\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 setDatabaseDeletedListener(): void {\n // No op.\n }\n\n setNetworkEnabled(): void {\n // No op.\n }\n\n getIndexManager(user: User): MemoryIndexManager {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n let overlay = this.overlays[user.toKey()];\n if (!overlay) {\n overlay = new MemoryDocumentOverlayCache();\n this.overlays[user.toKey()] = overlay;\n }\n return overlay;\n }\n\n getMutationQueue(user: User, indexManager: IndexManager): MutationQueue {\n let queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue(indexManager, this.referenceDelegate);\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 getBundleCache(): MemoryBundleCache {\n return this.bundleCache;\n }\n\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T> {\n logDebug(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 Object.values(this.mutationQueues).map(\n queue => () => queue.containsKey(transaction, key)\n )\n );\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */\nexport class MemoryTransaction extends PersistenceTransaction {\n constructor(readonly currentSequenceNumber: ListenSequenceNumber) {\n super();\n }\n}\n\nexport interface MemoryReferenceDelegate extends ReferenceDelegate {\n documentSize(doc: Document): number;\n onTransactionStarted(): void;\n onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise<void>;\n}\n\nexport class MemoryEagerDelegate implements MemoryReferenceDelegate {\n /** Tracks all documents that are active in Query views. */\n private localViewReferences: ReferenceSet = new ReferenceSet();\n /** The list of documents that are potentially GCed after each transaction. */\n private _orphanedDocuments: Set</* path= */ string> | null = null;\n\n private constructor(private readonly persistence: MemoryPersistence) {}\n\n static factory(persistence: MemoryPersistence): MemoryEagerDelegate {\n return new MemoryEagerDelegate(persistence);\n }\n\n private get orphanedDocuments(): Set<string> {\n if (!this._orphanedDocuments) {\n throw fail('orphanedDocuments is only valid during a transaction.');\n } else {\n return this._orphanedDocuments;\n }\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.localViewReferences.addReference(key, targetId);\n this.orphanedDocuments.delete(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.localViewReferences.removeReference(key, targetId);\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const orphaned = this.localViewReferences.removeReferencesForId(\n targetData.targetId\n );\n orphaned.forEach(key => this.orphanedDocuments.add(key.toString()));\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.toString()));\n })\n .next(() => cache.removeTargetData(txn, targetData));\n }\n\n onTransactionStarted(): void {\n this._orphanedDocuments = new Set<string>();\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 (path: string) => {\n const key = DocumentKey.fromPath(path);\n return this.isReferenced(txn, key).next(isReferenced => {\n if (!isReferenced) {\n changeBuffer.removeEntry(key, SnapshotVersion.min());\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.toString());\n } else {\n this.orphanedDocuments.add(key.toString());\n }\n });\n }\n\n documentSize(doc: Document): 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 () =>\n PersistencePromise.resolve(this.localViewReferences.containsKey(key)),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => this.persistence.mutationQueuesContainKey(txn, key)\n ]);\n }\n}\n\nexport class MemoryLruDelegate implements ReferenceDelegate, LruDelegate {\n private orphanedSequenceNumbers: ObjectMap<\n DocumentKey,\n ListenSequenceNumber\n > = new ObjectMap(\n k => encodeResourcePath(k.path),\n (l, r) => l.isEqual(r)\n );\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(\n private readonly persistence: MemoryPersistence,\n lruParams: LruParams\n ) {\n this.garbageCollector = newLruGarbageCollector(this, lruParams);\n }\n\n static factory(\n persistence: MemoryPersistence,\n lruParams: LruParams\n ): MemoryLruDelegate {\n return new MemoryLruDelegate(persistence, 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 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, SnapshotVersion.min());\n }\n });\n });\n return p.next(() => changeBuffer.apply(txn)).next(() => count);\n }\n\n markPotentiallyOrphaned(\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 targetId: TargetId,\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 targetId: TargetId,\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(document: Document): number {\n let documentSize = document.key.toString().length;\n if (document.isFoundDocument()) {\n documentSize += estimateByteSize(document.data.value);\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 () => 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport {\n dbDocumentSize,\n removeMutationBatch\n} from './indexeddb_mutation_batch_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { newIndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n DbCollectionParent,\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue,\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbTarget,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport {\n DbRemoteDocument as DbRemoteDocumentLegacy,\n DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy,\n DbRemoteDocumentKey as DbRemoteDocumentKeyLegacy\n} from './indexeddb_schema_legacy';\nimport {\n DbBundleKeyPath,\n DbBundleStore,\n DbClientMetadataKeyPath,\n DbClientMetadataStore,\n DbCollectionParentKey,\n DbCollectionParentKeyPath,\n DbCollectionParentStore,\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n DbDocumentOverlayKeyPath,\n DbDocumentOverlayStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n DbIndexConfigurationKeyPath,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n DbIndexEntryKeyPath,\n DbIndexEntryStore,\n DbIndexStateKeyPath,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n DbIndexStateStore,\n DbMutationBatchKey,\n DbMutationBatchKeyPath,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n DbMutationQueueKey,\n DbMutationQueueKeyPath,\n DbMutationQueueStore,\n DbNamedQueryKeyPath,\n DbNamedQueryStore,\n DbPrimaryClientStore,\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentKeyPath,\n DbRemoteDocumentStore,\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n DbTargetDocumentKey,\n DbTargetDocumentKeyPath,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetKeyPath,\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalDocumentsView } from './local_documents_view';\nimport {\n fromDbMutationBatch,\n fromDbTarget,\n LocalSerializer,\n toDbTarget\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { MemoryEagerDelegate, MemoryPersistence } from './memory_persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\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 debugAssert(\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('createOrUpgrade', txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createLegacyRemoteDocumentCache(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\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n });\n }\n\n if (fromVersion < 10 && toVersion >= 10) {\n p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n }\n\n if (fromVersion < 11 && toVersion >= 11) {\n p = p.next(() => {\n createBundlesStore(db);\n createNamedQueriesStore(db);\n });\n }\n\n if (fromVersion < 12 && toVersion >= 12) {\n p = p.next(() => {\n createDocumentOverlayStore(db);\n });\n }\n\n if (fromVersion < 13 && toVersion >= 13) {\n p = p\n .next(() => createRemoteDocumentCache(db))\n .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n }\n\n if (fromVersion < 14 && toVersion >= 14) {\n p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n }\n\n if (fromVersion < 15 && toVersion >= 15) {\n p = p.next(() => createFieldIndex(db));\n }\n\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n let byteSize = 0;\n return txn\n .store<DbRemoteDocumentKeyLegacy, DbRemoteDocumentLegacy>(\n DbRemoteDocumentStoreLegacy\n )\n .iterate((_, doc) => {\n byteSize += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata: DbRemoteDocumentGlobal = { byteSize };\n return txn\n .store<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal>(\n DbRemoteDocumentGlobalStore\n )\n .put(DbRemoteDocumentGlobalKey, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const queuesStore = txn.store<DbMutationQueueKey, DbMutationQueue>(\n DbMutationQueueStore\n );\n const mutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatchStore\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(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n hardAssert(\n dbBatch.userId === queue.userId,\n `Cannot process batch ${dbBatch.batchId} from unexpected user`\n );\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(\n () => {}\n );\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 >(DbTargetDocumentStore);\n const documentsStore = txn.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentKeyLegacy\n >(DbRemoteDocumentStoreLegacy);\n const globalTargetStore = txn.store<DbTargetGlobalKey, DbTargetGlobal>(\n DbTargetGlobalStore\n );\n\n return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n debugAssert(\n !!metadata,\n 'Metadata should have been written during the version 3 migration'\n );\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise<void> => {\n return documentTargetStore.put({\n targetId: 0,\n path: encodeResourcePath(path),\n sequenceNumber: metadata!.highestListenSequenceNumber!\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(DbCollectionParentStore, {\n keyPath: DbCollectionParentKeyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParentStore);\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: encodeResourcePath(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store<DbRemoteDocumentKeyLegacy, DbRemoteDocumentLegacy>(\n DbRemoteDocumentStoreLegacy\n )\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 DbDocumentMutationStore\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decodeResourcePath(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n\n private rewriteCanonicalIds(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const targetStore = txn.store<DbTargetKey, DbTarget>(DbTargetStore);\n return targetStore.iterate((key, originalDbTarget) => {\n const originalTargetData = fromDbTarget(originalDbTarget);\n const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n return targetStore.put(updatedDbTarget);\n });\n }\n\n private rewriteRemoteDocumentCache(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise<void> {\n const legacyRemoteDocumentStore = transaction.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentLegacy\n >(DbRemoteDocumentStoreLegacy);\n\n const writes: Array<PersistencePromise<void>> = [];\n return legacyRemoteDocumentStore\n .iterate((_, legacyDocument) => {\n const remoteDocumentStore = transaction.store<\n DbRemoteDocumentKey,\n DbRemoteDocument\n >(DbRemoteDocumentStore);\n\n const path = extractKey(legacyDocument).path.toArray();\n const dbRemoteDocument = {\n prefixPath: path.slice(0, path.length - 2),\n collectionGroup: path[path.length - 2],\n documentId: path[path.length - 1],\n readTime: legacyDocument.readTime || [0, 0],\n unknownDocument: legacyDocument.unknownDocument,\n noDocument: legacyDocument.noDocument,\n document: legacyDocument.document,\n hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n };\n writes.push(remoteDocumentStore.put(dbRemoteDocument));\n })\n .next(() => PersistencePromise.waitFor(writes));\n }\n\n private runOverlayMigration(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise<void> {\n const mutationsStore = transaction.store<\n DbMutationBatchKey,\n DbMutationBatch\n >(DbMutationBatchStore);\n\n const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n this.serializer\n );\n const memoryPersistence = new MemoryPersistence(\n MemoryEagerDelegate.factory,\n this.serializer.remoteSerializer\n );\n\n return mutationsStore.loadAll().next(dbBatches => {\n const userToDocumentSet = new Map<string, DocumentKeySet>();\n dbBatches.forEach(dbBatch => {\n let documentSet =\n userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n userToDocumentSet.set(dbBatch.userId, documentSet);\n });\n return PersistencePromise.forEach(\n userToDocumentSet,\n (allDocumentKeysForUser, userId) => {\n const user = new User(userId);\n const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n this.serializer,\n user\n );\n // NOTE: The index manager and the reference delegate are\n // irrelevant for the purpose of recalculating and saving\n // overlays. We can therefore simply use the memory\n // implementation.\n const indexManager = memoryPersistence.getIndexManager(user);\n const mutationQueue = IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n memoryPersistence.referenceDelegate\n );\n const localDocumentsView = new LocalDocumentsView(\n remoteDocumentCache,\n mutationQueue,\n documentOverlayCache,\n indexManager\n );\n return localDocumentsView\n .recalculateAndSaveOverlaysForDocumentKeys(\n new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n allDocumentKeysForUser\n )\n .next();\n }\n );\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueueStore, {\n keyPath: DbMutationQueueKeyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutationStore);\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 DbMutationBatchStore\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatchStore);\n\n const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatchStore\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n keyPath: DbRemoteDocumentKeyPath\n });\n remoteDocumentStore.createIndex(\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath\n );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n keyPath: DbTargetDocumentKeyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTargetStore, {\n keyPath: DbTargetKeyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocumentStore);\n db.deleteObjectStore(DbTargetStore);\n db.deleteObjectStore(DbTargetGlobalStore);\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 txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise<void> {\n const globalStore = txn.store<DbTargetGlobalKey, DbTargetGlobal>(\n DbTargetGlobalStore\n );\n const metadata: DbTargetGlobal = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadataStore, {\n keyPath: DbClientMetadataKeyPath\n });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n db.createObjectStore(DbBundleStore, {\n keyPath: DbBundleKeyPath\n });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n db.createObjectStore(DbNamedQueryStore, {\n keyPath: DbNamedQueryKeyPath\n });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n const indexConfigurationStore = db.createObjectStore(\n DbIndexConfigurationStore,\n {\n keyPath: DbIndexConfigurationKeyPath,\n autoIncrement: true\n }\n );\n indexConfigurationStore.createIndex(\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n { unique: false }\n );\n\n const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n keyPath: DbIndexStateKeyPath\n });\n indexStateStore.createIndex(\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n { unique: false }\n );\n\n const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n keyPath: DbIndexEntryKeyPath\n });\n indexEntryStore.createIndex(\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n { unique: false }\n );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n keyPath: DbDocumentOverlayKeyPath\n });\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n { unique: false }\n );\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n { unique: false }\n );\n}\n\nfunction extractKey(remoteDoc: DbRemoteDocumentLegacy): DocumentKey {\n if (remoteDoc.document) {\n return new DocumentKey(\n ResourcePath.fromString(remoteDoc.document.name!).popFirst(5)\n );\n } else if (remoteDoc.noDocument) {\n return DocumentKey.fromSegments(remoteDoc.noDocument.path);\n } else if (remoteDoc.unknownDocument) {\n return DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafari } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { DatabaseId } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { DocumentLike, WindowLike } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbBundleCache } from './indexeddb_bundle_cache';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport {\n IndexedDbRemoteDocumentCache,\n newIndexedDbRemoteDocumentCache\n} from './indexeddb_remote_document_cache';\nimport {\n DbClientMetadata,\n DbPrimaryClient,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport { SchemaConverter } from './indexeddb_schema_converter';\nimport {\n DbClientMetadataKey,\n DbClientMetadataStore,\n DbPrimaryClientKey,\n DbPrimaryClientStore,\n getObjectStores\n} from './indexeddb_sentinels';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { getStore, IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalSerializer } from './local_serializer';\nimport { LruParams } from './lru_garbage_collector';\nimport { Persistence, PrimaryStateListener } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence_transaction';\nimport { ClientId } from './shared_client_state';\nimport {\n isIndexedDbTransactionError,\n SimpleDb,\n SimpleDbStore\n} 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 'Failed to obtain exclusive access to the persistence layer. To allow ' +\n 'shared access, multi-tab synchronization has to be enabled in all tabs. ' +\n 'If you are using `experimentalForceOwningTab:true`, make sure that only ' +\n 'one tab has persistence enabled at any given time.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing IndexedDB or is known to have ' +\n 'an incomplete implementation. Offline 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\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 */\nexport const MAIN_DATABASE = 'main';\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 private simpleDb: SimpleDb;\n\n private listenSequence: ListenSequence | null = null;\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: DelayedOperation<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 remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly bundleCache: IndexedDbBundleCache;\n private readonly webStorage: Storage | null;\n readonly referenceDelegate: IndexedDbLruDelegateImpl;\n\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n private readonly allowTabSynchronization: boolean,\n\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n private readonly window: WindowLike | null,\n private readonly document: DocumentLike | null,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer,\n\n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n private readonly forceOwningTab: boolean,\n private readonly schemaVersion = SCHEMA_VERSION\n ) {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);\n this.dbName = persistenceKey + MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.simpleDb = new SimpleDb(\n this.dbName,\n this.schemaVersion,\n new SchemaConverter(this.serializer)\n );\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);\n this.bundleCache = new IndexedDbBundleCache();\n if (this.window && this.window.localStorage) {\n this.webStorage = this.window.localStorage;\n } else {\n this.webStorage = null;\n if (forceOwningTab === false) {\n logError(\n LOG_TAG,\n 'LocalStorage is unavailable. As a result, persistence may not work ' +\n 'reliably. In particular enablePersistence() could fail immediately ' +\n 'after refreshing the page.'\n );\n }\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */\n start(): Promise<void> {\n debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => {\n if (!this.isPrimary && !this.allowTabSynchronization) {\n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.runTransaction(\n 'getHighestListenSequenceNumber',\n 'readonly',\n txn => this.targetCache.getHighestSequenceNumber(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 /**\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 this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\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 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 /**\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 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.runTransaction(\n 'updateClientMetadataAndTryBecomePrimary',\n 'readwrite',\n txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n })\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\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 )\n .catch(e => {\n if (isIndexedDbTransactionError(e)) {\n logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return this.isPrimary;\n }\n\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n logDebug(\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.enqueueRetryable(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise<boolean> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise<void> {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = getStore<DbClientMetadataKey, DbClientMetadata>(\n txn,\n DbClientMetadataStore\n );\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.webStorage) {\n for (const inactiveClient of inactiveClients) {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\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: PersistenceTransaction\n ): PersistencePromise<boolean> {\n if (this.forceOwningTab) {\n return PersistencePromise.resolve<boolean>(true);\n }\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClientKey)\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 // - the `forceOwningTab` setting was passed in.\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 logDebug(\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\n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.simpleDb.runTransaction(\n 'shutdown',\n 'readwrite',\n [DbPrimaryClientStore, DbClientMetadataStore],\n simpleDbTxn => {\n const persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n ListenSequence.INVALID\n );\n return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n this.removeClientMetadata(persistenceTransaction)\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 /**\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 return this.runTransaction('getActiveClients', 'readonly', 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 get started(): boolean {\n return this._started;\n }\n\n getMutationQueue(\n user: User,\n indexManager: IndexManager\n ): IndexedDbMutationQueue {\n debugAssert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n debugAssert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n debugAssert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(user: User): IndexManager {\n debugAssert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return new IndexedDbIndexManager(\n user,\n this.serializer.remoteSerializer.databaseId\n );\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n debugAssert(\n this.started,\n 'Cannot initialize IndexedDbDocumentOverlayCache before persistence is started.'\n );\n return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);\n }\n\n getBundleCache(): BundleCache {\n debugAssert(\n this.started,\n 'Cannot initialize BundleCache before persistence is started.'\n );\n return this.bundleCache;\n }\n\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T> {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n const objectStores = getObjectStores(this.schemaVersion);\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(action, simpleDbMode, objectStores, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence\n ? this.listenSequence.next()\n : ListenSequence.INVALID\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(persistenceTransaction)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(persistenceTransaction);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n logError(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\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(\n persistenceTransaction\n ).next(() => result);\n });\n } else {\n return this.verifyAllowTabSynchronization(\n persistenceTransaction\n ).next(() => transactionOperation(persistenceTransaction));\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: PersistenceTransaction\n ): PersistencePromise<void> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).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 (\n !this.forceOwningTab &&\n (!this.allowTabSynchronization ||\n !currentPrimary!.allowTabSynchronization)\n ) {\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: PersistenceTransaction\n ): PersistencePromise<void> {\n const newPrimary: DbPrimaryClient = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n logDebug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClientKey);\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 logError(\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 debugAssert(\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 const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n if (\n isSafari() &&\n (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n navigator.userAgent.match(safariIndexdbBugVersionRegex))\n ) {\n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n }\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('pagehide', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n debugAssert(\n typeof this.window?.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window!.removeEventListener('pagehide', 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(\n this.zombiedClientLocalStorageKey(clientId)\n ) !== null;\n logDebug(\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 logError(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 if (!this.webStorage) {\n return;\n }\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 logError('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n if (!this.webStorage) {\n return;\n }\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: PersistenceTransaction\n): SimpleDbStore<DbPrimaryClientKey, DbPrimaryClient> {\n return getStore<DbPrimaryClientKey, DbPrimaryClient>(\n txn,\n DbPrimaryClientStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbClientMetadataKey, DbClientMetadata> {\n return getStore<DbClientMetadataKey, DbClientMetadata>(\n txn,\n DbClientMetadataStore\n );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n databaseId: DatabaseId,\n persistenceKey: string\n): 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 = databaseId.projectId;\n if (!databaseId.isDefaultDatabase) {\n database += '.' + databaseId.database;\n }\n\n return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n persistenceKey: string\n): Promise<void> {\n if (!SimpleDb.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { IndexKind } from '../model/field_index';\nimport { BundledQuery } from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n DocumentsTarget as ProtoDocumentsTarget,\n QueryTarget as ProtoQueryTarget,\n Write as ProtoWrite\n} from '../protos/firestore_proto_api';\n\nimport { EncodedResourcePath } from './encoded_resource_path';\nimport { DbTimestampKey } from './indexeddb_sentinels';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document 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 * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n */\n\nexport const SCHEMA_VERSION = 15;\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport interface DbTimestamp {\n seconds: number;\n nanoseconds: number;\n}\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 interface DbPrimaryClient {\n ownerId: string;\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization: boolean;\n leaseTimestampMs: number;\n}\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 interface DbMutationQueue {\n /**\n * The normalized user ID to which this queue belongs.\n */\n 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 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 * NOTE: this is deprecated and no longer used by the code.\n */\n lastStreamToken: string;\n}\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 interface DbMutationBatch {\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId: string;\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n batchId: BatchId;\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n 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 baseMutations?: ProtoWrite[];\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */\n mutations: ProtoWrite[];\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 interface DbDocumentMutation {}\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 interface DbNoDocument {\n path: string[];\n 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 interface DbUnknownDocument {\n path: string[];\n 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 * The document key is split up across `prefixPath`, `collectionGroup` and\n * `documentId`.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport interface DbRemoteDocument {\n /** The path to the document's collection (excluding). */\n prefixPath: string[];\n\n /** The collection ID the document is direclty nested under. */\n collectionGroup: string;\n\n /** The document ID. */\n documentId: string;\n\n /** When the document was read from the backend. */\n readTime: DbTimestampKey;\n\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 unknownDocument?: DbUnknownDocument;\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument?: DbNoDocument;\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document?: ProtoDocument;\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 hasCommittedMutations: boolean;\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport interface DbRemoteDocumentGlobal {\n /**\n * Approximately the total size in bytes of all the\n * documents in the document cache.\n */\n byteSize: number;\n}\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 = ProtoQueryTarget | ProtoDocumentsTarget;\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 interface DbTarget {\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 targetId: TargetId;\n /**\n * The canonical string representing this query. This is not unique.\n */\n 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 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 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 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 lastLimboFreeSnapshotVersion?: DbTimestamp;\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 query: DbQuery;\n}\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 interface DbTargetDocument {\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n targetId: TargetId;\n /**\n * The path to the document, as encoded in the key.\n */\n 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 sequenceNumber?: ListenSequenceNumber;\n}\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 interface DbTargetGlobal {\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId: TargetId;\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n 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 lastRemoteSnapshotVersion: DbTimestamp;\n /**\n * The number of targets persisted.\n */\n targetCount: number;\n}\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 interface DbCollectionParent {\n /**\n * The collectionId (e.g. 'messages')\n */\n 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 parent: EncodedResourcePath;\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 interface DbClientMetadata {\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 clientId: string;\n /** The last time this state was updated. */\n updateTimeMs: number;\n /** Whether the client's network connection is enabled. */\n networkEnabled: boolean;\n /** Whether this client is running in a foreground tab. */\n inForeground: boolean;\n}\n\n/** An object representing a bundle loaded by the SDK. */\nexport interface DbBundle {\n /** The ID of the loaded bundle. */\n bundleId: string;\n /** The create time of the loaded bundle. */\n createTime: DbTimestamp;\n /** The schema version of the loaded bundle. */\n version: number;\n}\n\n/** An object representing a named query loaded by the SDK via a bundle. */\nexport interface DbNamedQuery {\n /** The name of the query. */\n name: string;\n /** The read time of the results saved in the bundle from the named query. */\n readTime: DbTimestamp;\n /** The query saved in the bundle. */\n bundledQuery: BundledQuery;\n}\n\n/** An object representing the global configuration for a field index. */\nexport interface DbIndexConfiguration {\n /**\n * The index id for this entry. Undefined for indexes that are not yet\n * persisted.\n */\n indexId?: number;\n /** The collection group this index belongs to. */\n collectionGroup: string;\n /** The fields to index for this index. */\n fields: Array<[name: string, kind: IndexKind]>;\n}\n\n/**\n * An object describing how up-to-date the index backfill is for each user and\n * index.\n */\nexport interface DbIndexState {\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /**\n * A number that indicates when the index was last updated (relative to\n * other indexes).\n */\n sequenceNumber: number;\n /**\n * The latest read time that has been indexed by Firestore for this field\n * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed.\n */\n readTime: DbTimestamp;\n /**\n * The last document that has been indexed for this field index. Empty if\n * no documents have been indexed.\n */\n documentKey: EncodedResourcePath;\n /**\n * The largest mutation batch id that has been processed for this index. -1\n * if no mutations have been indexed.\n */\n largestBatchId: number;\n}\n\n/** An object that stores the encoded entries for all documents and fields. */\nexport interface DbIndexEntry {\n // TODO(indexing): Consider just storing `orderedDocumentKey` and decoding\n // the ordered key into a document key. This would reduce storage space on\n // disk but require us to port parts of OrderedCodeReader.\n\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /** The encoded array index value for this entry. */\n arrayValue: Uint8Array;\n /** The encoded directional value for equality and inequality filters. */\n directionalValue: Uint8Array;\n /**\n * The document key this entry points to. This entry is encoded by an ordered\n * encoder to match the key order of the index.\n */\n orderedDocumentKey: Uint8Array;\n /** The segments of the document key this entry points to. */\n documentKey: string[];\n}\n\n/**\n * An object representing a document overlay.\n */\nexport interface DbDocumentOverlay {\n /** The user ID to whom this overlay belongs. */\n userId: string;\n /** The path to the collection that contains the document. */\n collectionPath: string;\n /** The ID (key) of the document within the collection. */\n documentId: string;\n /** The collection group to which the document belongs. */\n collectionGroup: string;\n /** The largest batch ID that's been applied for this overlay. */\n largestBatchId: number;\n /** The overlay mutation. */\n overlayMutation: ProtoWrite;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A tracker to keep a record of important details during database local query\n * execution.\n */\nexport class QueryContext {\n /**\n * Counts the number of documents passed through during local query execution.\n */\n private _documentReadCount = 0;\n\n get documentReadCount(): number {\n return this._documentReadCount;\n }\n\n incrementDocumentReadCount(amount: number): void {\n this._documentReadCount += amount;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA, isSafari } from '@firebase/util';\n\nimport {\n LimitType,\n newQueryComparator,\n Query,\n queryMatches,\n queryMatchesAllDocuments,\n queryToTarget,\n queryWithLimit,\n stringifyQuery\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport {\n IndexOffset,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { Iterable } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { SimpleDb } from './simple_db';\n\nconst DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE = 100;\n\n/**\n * This cost represents the evaluation result of\n * (([index, docKey] + [docKey, docContent]) per document in the result set)\n * / ([docKey, docContent] per documents in full collection scan) coming from\n * experiment [enter PR experiment URL here].\n */\nfunction getDefaultRelativeIndexReadCostPerDocument(): number {\n // These values were derived from an experiment where several members of the\n // Firestore SDK team ran a performance test in various environments.\n // Googlers can see b/299284287 for details.\n if (isSafari()) {\n return 8;\n } else if (SimpleDb.getAndroidVersion(getUA()) > 0) {\n return 6;\n } else {\n return 4;\n }\n}\n\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */\nexport class QueryEngine {\n private localDocumentsView!: LocalDocumentsView;\n private indexManager!: IndexManager;\n private initialized = false;\n\n indexAutoCreationEnabled = false;\n\n /**\n * SDK only decides whether it should create index when collection size is\n * larger than this.\n */\n indexAutoCreationMinCollectionSize =\n DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE;\n\n relativeIndexReadCostPerDocument =\n getDefaultRelativeIndexReadCostPerDocument();\n\n /** Sets the document view to query against. */\n initialize(\n localDocuments: LocalDocumentsView,\n indexManager: IndexManager\n ): void {\n this.localDocumentsView = localDocuments;\n this.indexManager = indexManager;\n this.initialized = true;\n }\n\n /** Returns all local documents matching the specified query. */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n lastLimboFreeSnapshotVersion: SnapshotVersion,\n remoteKeys: DocumentKeySet\n ): PersistencePromise<DocumentMap> {\n debugAssert(this.initialized, 'initialize() not called');\n\n // Stores the result from executing the query; using this object is more\n // convenient than passing the result between steps of the persistence\n // transaction and improves readability comparatively.\n const queryResult: { result: DocumentMap | null } = { result: null };\n\n return this.performQueryUsingIndex(transaction, query)\n .next(result => {\n queryResult.result = result;\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n return this.performQueryUsingRemoteKeys(\n transaction,\n query,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n ).next(result => {\n queryResult.result = result;\n });\n })\n .next(() => {\n if (queryResult.result) {\n return;\n }\n const context = new QueryContext();\n return this.executeFullCollectionScan(transaction, query, context).next(\n result => {\n queryResult.result = result;\n if (this.indexAutoCreationEnabled) {\n return this.createCacheIndexes(\n transaction,\n query,\n context,\n result.size\n );\n }\n }\n );\n })\n .next(() => queryResult.result!);\n }\n\n createCacheIndexes(\n transaction: PersistenceTransaction,\n query: Query,\n context: QueryContext,\n resultSize: number\n ): PersistencePromise<void> {\n if (context.documentReadCount < this.indexAutoCreationMinCollectionSize) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'SDK will not create cache indexes for query:',\n stringifyQuery(query),\n 'since it only creates cache indexes for collection contains',\n 'more than or equal to',\n this.indexAutoCreationMinCollectionSize,\n 'documents'\n );\n }\n return PersistencePromise.resolve();\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Query:',\n stringifyQuery(query),\n 'scans',\n context.documentReadCount,\n 'local documents and returns',\n resultSize,\n 'documents as results.'\n );\n }\n\n if (\n context.documentReadCount >\n this.relativeIndexReadCostPerDocument * resultSize\n ) {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'The SDK decides to create cache indexes for query:',\n stringifyQuery(query),\n 'as using cache indexes may help improve performance.'\n );\n }\n return this.indexManager.createTargetIndexes(\n transaction,\n queryToTarget(query)\n );\n }\n\n return PersistencePromise.resolve();\n }\n\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */\n private performQueryUsingIndex(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<DocumentMap | null> {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n let target = queryToTarget(query);\n return this.indexManager\n .getIndexType(transaction, target)\n .next(indexType => {\n if (indexType === IndexType.NONE) {\n // The target cannot be served from any index.\n return null;\n }\n\n if (query.limit !== null && indexType === IndexType.PARTIAL) {\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n query = queryWithLimit(query, null, LimitType.First);\n target = queryToTarget(query);\n }\n\n return this.indexManager\n .getDocumentsMatchingTarget(transaction, target)\n .next(keys => {\n debugAssert(\n !!keys,\n 'Index manager must return results for partial and full indexes.'\n );\n const sortedKeys = documentKeySet(...keys);\n return this.localDocumentsView\n .getDocuments(transaction, sortedKeys)\n .next(indexedDocuments => {\n return this.indexManager\n .getMinOffset(transaction, target)\n .next(offset => {\n const previousResults = this.applyQuery(\n query,\n indexedDocuments\n );\n\n if (\n this.needsRefill(\n query,\n previousResults,\n sortedKeys,\n offset.readTime\n )\n ) {\n // A limit query whose boundaries change due to local\n // edits can be re-run against the cache by excluding the\n // limit. This ensures that all documents that match the\n // query's filters are included in the result set. The SDK\n // can then apply the limit once all local edits are\n // incorporated.\n return this.performQueryUsingIndex(\n transaction,\n queryWithLimit(query, null, LimitType.First)\n );\n }\n\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n offset\n ) as PersistencePromise<DocumentMap | null>;\n });\n });\n });\n });\n }\n\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */\n private performQueryUsingRemoteKeys(\n transaction: PersistenceTransaction,\n query: Query,\n remoteKeys: DocumentKeySet,\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): PersistencePromise<DocumentMap | null> {\n if (queryMatchesAllDocuments(query)) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return PersistencePromise.resolve<DocumentMap | null>(null);\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 PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(\n documents => {\n const previousResults = this.applyQuery(query, documents);\n\n if (\n this.needsRefill(\n query,\n previousResults,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n )\n ) {\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Re-using previous result from %s to execute query: %s',\n lastLimboFreeSnapshotVersion.toString(),\n stringifyQuery(query)\n );\n }\n\n // Retrieve all results for documents that were updated since the last\n // limbo-document free remote snapshot.\n return this.appendRemainingResults(\n transaction,\n previousResults,\n query,\n newIndexOffsetSuccessorFromReadTime(\n lastLimboFreeSnapshotVersion,\n INITIAL_LARGEST_BATCH_ID\n )\n ).next<DocumentMap | null>(results => results);\n }\n );\n }\n\n /** Applies the query filter and sorting to the provided documents. */\n private applyQuery(\n query: Query,\n documents: DocumentMap\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>(newQueryComparator(query));\n documents.forEach((_, maybeDoc) => {\n if (queryMatches(query, 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 query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */\n private needsRefill(\n query: Query,\n sortedPreviousResults: SortedSet<Document>,\n remoteKeys: DocumentKeySet,\n limboFreeSnapshotVersion: SnapshotVersion\n ): boolean {\n if (query.limit === null) {\n // Queries without limits do not need to be refilled.\n return false;\n }\n\n if (remoteKeys.size !== sortedPreviousResults.size) {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\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 query.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 context: QueryContext\n ): PersistencePromise<DocumentMap> {\n if (getLogLevel() <= LogLevel.DEBUG) {\n logDebug(\n 'QueryEngine',\n 'Using full collection scan to execute query:',\n stringifyQuery(query)\n );\n }\n\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n IndexOffset.min(),\n context\n );\n }\n\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */\n private appendRemainingResults(\n transaction: PersistenceTransaction,\n indexedResults: Iterable<Document>,\n query: Query,\n offset: IndexOffset\n ): PersistencePromise<DocumentMap> {\n // Retrieve all results for documents that were updated since the offset.\n return this.localDocumentsView\n .getDocumentsMatchingQuery(transaction, query, offset)\n .next(remainingResults => {\n // Merge with existing results\n indexedResults.forEach(d => {\n remainingResults = remainingResults.insert(d.key, d);\n });\n return remainingResults;\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BundleConverter, BundledDocuments, NamedQuery } from '../core/bundle';\nimport {\n newQueryForPath,\n Query,\n queryCollectionGroup,\n queryToTarget\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { BatchId, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n convertOverlayedDocumentMapToDocumentMap,\n documentKeySet,\n DocumentKeySet,\n DocumentMap,\n mutableDocumentMap,\n MutableDocumentMap,\n OverlayedDocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldIndex,\n fieldIndexSemanticComparator,\n INITIAL_LARGEST_BATCH_ID,\n newIndexOffsetSuccessorFromReadTime\n} from '../model/field_index';\nimport {\n mutationExtractBaseValue,\n Mutation,\n PatchMutation,\n Precondition\n} from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { extractFieldMask } from '../model/object_value';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { fromVersion, JsonProtoSerializer } from '../remote/serializer';\nimport { diffArrays } from '../util/array';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { fromBundledQuery } from './local_serializer';\nimport { LocalStore } from './local_store';\nimport { LocalViewChanges } from './local_view_changes';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryEngine } from './query_engine';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { ClientId } from './shared_client_state';\nimport { isIndexedDbTransactionError } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData, TargetPurpose } from './target_data';\n\nexport const LOG_TAG = 'LocalStore';\n\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 */\nconst RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n\n/** The result of a write to the local store. */\nexport interface LocalWriteResult {\n batchId: BatchId;\n changes: DocumentMap;\n}\n\n/** The result of a user-change operation in the local store. */\nexport interface UserChangeResult {\n readonly affectedDocuments: DocumentMap;\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 * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass LocalStoreImpl implements LocalStore {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n mutationQueue!: MutationQueue;\n\n /**\n * The overlays that can be used to short circuit applying all mutations from\n * mutation queue.\n */\n documentOverlayCache!: DocumentOverlayCache;\n\n /** The set of all cached remote documents. */\n remoteDocuments: RemoteDocumentCache;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n localDocuments!: LocalDocumentsView;\n\n /** Manages the list of active field and collection indices. */\n indexManager!: IndexManager;\n\n /** The set of all cached bundle metadata and named queries. */\n bundleCache: BundleCache;\n\n /** Maps a target to its `TargetData`. */\n 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 targetDataByTarget = new SortedMap<TargetId, TargetData>(primitiveComparator);\n\n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n targetIdByTarget = new ObjectMap<Target, TargetId>(\n t => canonifyTarget(t),\n targetEquals\n );\n\n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n collectionGroupReadTime = new Map<string, SnapshotVersion>();\n\n constructor(\n /** Manages our in-memory or durable persistence. */\n readonly persistence: Persistence,\n readonly queryEngine: QueryEngine,\n initialUser: User,\n readonly serializer: JsonProtoSerializer\n ) {\n debugAssert(\n persistence.started,\n 'LocalStore was passed an unstarted persistence implementation'\n );\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.targetCache = persistence.getTargetCache();\n this.bundleCache = persistence.getBundleCache();\n\n this.initializeUserComponents(initialUser);\n }\n\n initializeUserComponents(user: User): void {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(user);\n this.indexManager = this.persistence.getIndexManager(user);\n this.mutationQueue = this.persistence.getMutationQueue(\n user,\n this.indexManager\n );\n this.localDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n this.mutationQueue,\n this.documentOverlayCache,\n this.indexManager\n );\n this.remoteDocuments.setIndexManager(this.indexManager);\n this.queryEngine.initialize(this.localDocuments, this.indexManager);\n }\n\n collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults> {\n return this.persistence.runTransaction(\n 'Collect garbage',\n 'readwrite-primary',\n txn => garbageCollector.collect(txn, this.targetDataByTarget)\n );\n }\n}\n\ninterface DocumentChangeResult {\n changedDocuments: MutableDocumentMap;\n existenceChangedKeys: DocumentKeySet;\n}\n\nexport function newLocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence: Persistence,\n queryEngine: QueryEngine,\n initialUser: User,\n serializer: JsonProtoSerializer\n): LocalStore {\n return new LocalStoreImpl(persistence, queryEngine, initialUser, serializer);\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.\nexport async function localStoreHandleUserChange(\n localStore: LocalStore,\n user: User\n): Promise<UserChangeResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n const result = await localStoreImpl.persistence.runTransaction(\n 'Handle user change',\n 'readonly',\n txn => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let oldBatches: MutationBatch[];\n return localStoreImpl.mutationQueue\n .getAllMutationBatches(txn)\n .next(promisedOldBatches => {\n oldBatches = promisedOldBatches;\n localStoreImpl.initializeUserComponents(user);\n return localStoreImpl.mutationQueue.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 localStoreImpl.localDocuments\n .getDocuments(txn, changedKeys)\n .next(affectedDocuments => {\n return {\n affectedDocuments,\n removedBatchIds,\n addedBatchIds\n };\n });\n });\n }\n );\n\n return result;\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\nexport function localStoreWriteLocally(\n localStore: LocalStore,\n mutations: Mutation[]\n): Promise<LocalWriteResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const localWriteTime = Timestamp.now();\n const keys = mutations.reduce((keys, m) => keys.add(m.key), documentKeySet());\n\n let overlayedDocuments: OverlayedDocumentMap;\n let mutationBatch: MutationBatch;\n\n return localStoreImpl.persistence\n .runTransaction('Locally write mutations', 'readwrite', txn => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let remoteDocs = mutableDocumentMap();\n let docsWithoutRemoteVersion = documentKeySet();\n return localStoreImpl.remoteDocuments\n .getEntries(txn, keys)\n .next(docs => {\n remoteDocs = docs;\n remoteDocs.forEach((key, doc) => {\n if (!doc.isValidDocument()) {\n docsWithoutRemoteVersion = docsWithoutRemoteVersion.add(key);\n }\n });\n })\n .next(() => {\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 localStoreImpl.localDocuments.getOverlayedDocuments(\n txn,\n remoteDocs\n );\n })\n .next((docs: OverlayedDocumentMap) => {\n overlayedDocuments = 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 = mutationExtractBaseValue(\n mutation,\n overlayedDocuments.get(mutation.key)!.overlayedDocument\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 extractFieldMask(baseValue.value.mapValue),\n Precondition.exists(true)\n )\n );\n }\n }\n\n return localStoreImpl.mutationQueue.addMutationBatch(\n txn,\n localWriteTime,\n baseMutations,\n mutations\n );\n })\n .next(batch => {\n mutationBatch = batch;\n const overlays = batch.applyToLocalDocumentSet(\n overlayedDocuments,\n docsWithoutRemoteVersion\n );\n return localStoreImpl.documentOverlayCache.saveOverlays(\n txn,\n batch.batchId,\n overlays\n );\n });\n })\n .then(() => ({\n batchId: mutationBatch.batchId,\n changes: convertOverlayedDocumentMapToDocumentMap(overlayedDocuments)\n }));\n}\n\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nexport function localStoreAcknowledgeBatch(\n localStore: LocalStore,\n batchResult: MutationBatchResult\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Acknowledge batch',\n 'readwrite-primary',\n txn => {\n const affected = batchResult.batch.keys();\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n return applyWriteToRemoteDocuments(\n localStoreImpl,\n txn,\n batchResult,\n documentBuffer\n )\n .next(() => documentBuffer.apply(txn))\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affected,\n batchResult.batch.batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n getKeysWithTransformResults(batchResult)\n )\n )\n .next(() => localStoreImpl.localDocuments.getDocuments(txn, affected));\n }\n );\n}\n\nfunction getKeysWithTransformResults(\n batchResult: MutationBatchResult\n): DocumentKeySet {\n let result = documentKeySet();\n\n for (let i = 0; i < batchResult.mutationResults.length; ++i) {\n const mutationResult = batchResult.mutationResults[i];\n if (mutationResult.transformResults.length > 0) {\n result = result.add(batchResult.batch.mutations[i].key);\n }\n }\n return result;\n}\n\n/**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\nexport function localStoreRejectBatch(\n localStore: LocalStore,\n batchId: BatchId\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Reject batch',\n 'readwrite-primary',\n txn => {\n let affectedKeys: DocumentKeySet;\n return localStoreImpl.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next((batch: MutationBatch | null) => {\n hardAssert(batch !== null, 'Attempt to reject nonexistent batch!');\n affectedKeys = batch.keys();\n return localStoreImpl.mutationQueue.removeMutationBatch(txn, batch);\n })\n .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn))\n .next(() =>\n localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(\n txn,\n affectedKeys,\n batchId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(\n txn,\n affectedKeys\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getDocuments(txn, affectedKeys)\n );\n }\n );\n}\n\n/**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */\nexport function localStoreGetHighestUnacknowledgedBatchId(\n localStore: LocalStore\n): Promise<BatchId> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get highest unacknowledged batch id',\n 'readonly',\n txn => localStoreImpl.mutationQueue.getHighestUnacknowledgedBatchId(txn)\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 */\nexport function localStoreGetLastRemoteSnapshotVersion(\n localStore: LocalStore\n): Promise<SnapshotVersion> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get last remote snapshot version',\n 'readonly',\n txn => localStoreImpl.targetCache.getLastRemoteSnapshotVersion(txn)\n );\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport function localStoreApplyRemoteEventToLocalCache(\n localStore: LocalStore,\n remoteEvent: RemoteEvent\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const remoteVersion = remoteEvent.snapshotVersion;\n let newTargetDataByTargetMap = localStoreImpl.targetDataByTarget;\n\n return localStoreImpl.persistence\n .runTransaction('Apply remote event', 'readwrite-primary', txn => {\n const documentBuffer = localStoreImpl.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 = localStoreImpl.targetDataByTarget;\n\n const promises = [] as Array<PersistencePromise<void>>;\n remoteEvent.targetChanges.forEach((change, targetId) => {\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 localStoreImpl.targetCache\n .removeMatchingKeys(txn, change.removedDocuments, targetId)\n .next(() => {\n return localStoreImpl.targetCache.addMatchingKeys(\n txn,\n change.addedDocuments,\n targetId\n );\n })\n );\n\n let newTargetData = oldTargetData.withSequenceNumber(\n txn.currentSequenceNumber\n );\n if (remoteEvent.targetMismatches.get(targetId) !== null) {\n newTargetData = newTargetData\n .withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n SnapshotVersion.min()\n )\n .withLastLimboFreeSnapshotVersion(SnapshotVersion.min());\n } else if (change.resumeToken.approximateByteSize() > 0) {\n newTargetData = newTargetData.withResumeToken(\n change.resumeToken,\n remoteVersion\n );\n }\n\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 (shouldPersistTargetData(oldTargetData, newTargetData, change)) {\n promises.push(\n localStoreImpl.targetCache.updateTargetData(txn, newTargetData)\n );\n }\n });\n\n let changedDocs = mutableDocumentMap();\n let existenceChangedKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(key => {\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\n promises.push(\n localStoreImpl.persistence.referenceDelegate.updateLimboDocument(\n txn,\n key\n )\n );\n }\n });\n\n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n promises.push(\n populateDocumentChangeBuffer(\n txn,\n documentBuffer,\n remoteEvent.documentUpdates\n ).next(result => {\n changedDocs = result.changedDocuments;\n existenceChangedKeys = result.existenceChangedKeys;\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 = localStoreImpl.targetCache\n .getLastRemoteSnapshotVersion(txn)\n .next(lastRemoteSnapshotVersion => {\n debugAssert(\n remoteVersion.compareTo(lastRemoteSnapshotVersion) >= 0,\n 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteSnapshotVersion\n );\n return localStoreImpl.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 localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n changedDocs,\n existenceChangedKeys\n )\n )\n .next(() => changedDocs);\n })\n .then(changedDocs => {\n localStoreImpl.targetDataByTarget = newTargetDataByTargetMap;\n return changedDocs;\n });\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */\nfunction populateDocumentChangeBuffer(\n txn: PersistenceTransaction,\n documentBuffer: RemoteDocumentChangeBuffer,\n documents: MutableDocumentMap\n): PersistencePromise<DocumentChangeResult> {\n let updatedKeys = documentKeySet();\n let existenceChangedKeys = documentKeySet();\n documents.forEach(k => (updatedKeys = updatedKeys.add(k)));\n return documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => {\n let changedDocuments = mutableDocumentMap();\n documents.forEach((key, doc) => {\n const existingDoc = existingDocs.get(key)!;\n\n // Check if see if there is a existence state change for this document.\n if (doc.isFoundDocument() !== existingDoc.isFoundDocument()) {\n existenceChangedKeys = existenceChangedKeys.add(key);\n }\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 (doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min())) {\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, doc.readTime);\n changedDocuments = changedDocuments.insert(key, doc);\n } else if (\n !existingDoc.isValidDocument() ||\n doc.version.compareTo(existingDoc.version) > 0 ||\n (doc.version.compareTo(existingDoc.version) === 0 &&\n existingDoc.hasPendingWrites)\n ) {\n debugAssert(\n !SnapshotVersion.min().isEqual(doc.readTime),\n 'Cannot add a document when the remote version is zero'\n );\n documentBuffer.addEntry(doc);\n changedDocuments = changedDocuments.insert(key, doc);\n } else {\n logDebug(\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 return { changedDocuments, existenceChangedKeys };\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 */\nfunction shouldPersistTargetData(\n oldTargetData: TargetData,\n newTargetData: TargetData,\n change: TargetChange\n): boolean {\n // Always persist target data if we don't already have a resume token.\n if (oldTargetData.resumeToken.approximateByteSize() === 0) {\n return true;\n }\n\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n const timeDelta =\n newTargetData.snapshotVersion.toMicroseconds() -\n oldTargetData.snapshotVersion.toMicroseconds();\n if (timeDelta >= 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 * Notifies local store of the changed views to locally pin documents.\n */\nexport async function localStoreNotifyLocalViewChanges(\n localStore: LocalStore,\n viewChanges: LocalViewChanges[]\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n try {\n await localStoreImpl.persistence.runTransaction(\n 'notifyLocalViewChanges',\n 'readwrite',\n txn => {\n return PersistencePromise.forEach(\n viewChanges,\n (viewChange: LocalViewChanges) => {\n return PersistencePromise.forEach(\n viewChange.addedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.addReference(\n txn,\n viewChange.targetId,\n key\n )\n ).next(() =>\n PersistencePromise.forEach(\n viewChange.removedKeys,\n (key: DocumentKey) =>\n localStoreImpl.persistence.referenceDelegate.removeReference(\n txn,\n viewChange.targetId,\n key\n )\n )\n );\n }\n );\n }\n );\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n logDebug(LOG_TAG, 'Failed to update sequence numbers: ' + e);\n } else {\n throw e;\n }\n }\n\n for (const viewChange of viewChanges) {\n const targetId = viewChange.targetId;\n\n if (!viewChange.fromCache) {\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\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 localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData);\n\n // TODO(b/272564316): Apply the optimization done on other platforms.\n // This is a problem for web because saving the updated targetData from\n // non-primary client conflicts with what primary client saved.\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 */\nexport function localStoreGetNextMutationBatch(\n localStore: LocalStore,\n afterBatchId?: BatchId\n): Promise<MutationBatch | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get next mutation batch',\n 'readonly',\n txn => {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return localStoreImpl.mutationQueue.getNextMutationBatchAfterBatchId(\n txn,\n afterBatchId\n );\n }\n );\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\nexport function localStoreReadDocument(\n localStore: LocalStore,\n key: DocumentKey\n): Promise<Document> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'read document',\n 'readonly',\n txn => localStoreImpl.localDocuments.getDocument(txn, key)\n );\n}\n\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nexport function localStoreAllocateTarget(\n localStore: LocalStore,\n target: Target\n): Promise<TargetData> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence\n .runTransaction('Allocate target', 'readwrite', txn => {\n let targetData: TargetData;\n return localStoreImpl.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 localStoreImpl.targetCache\n .allocateTargetId(txn)\n .next(targetId => {\n targetData = new TargetData(\n target,\n targetId,\n TargetPurpose.Listen,\n txn.currentSequenceNumber\n );\n return localStoreImpl.targetCache\n .addTargetData(txn, targetData)\n .next(() => targetData);\n });\n }\n });\n })\n .then(targetData => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(\n targetData.targetId\n );\n if (\n cachedTargetData === null ||\n targetData.snapshotVersion.compareTo(cachedTargetData.snapshotVersion) >\n 0\n ) {\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n targetData.targetId,\n targetData\n );\n localStoreImpl.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.\nexport function localStoreGetTargetData(\n localStore: LocalStore,\n transaction: PersistenceTransaction,\n target: Target\n): PersistencePromise<TargetData | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetId = localStoreImpl.targetIdByTarget.get(target);\n if (targetId !== undefined) {\n return PersistencePromise.resolve<TargetData | null>(\n localStoreImpl.targetDataByTarget.get(targetId)\n );\n } else {\n return localStoreImpl.targetCache.getTargetData(transaction, target);\n }\n}\n\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nexport async function localStoreReleaseTarget(\n localStore: LocalStore,\n targetId: number,\n keepPersistedTargetData: boolean\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetData = localStoreImpl.targetDataByTarget.get(targetId);\n debugAssert(\n targetData !== null,\n `Tried to release nonexistent target: ${targetId}`\n );\n\n const mode = keepPersistedTargetData ? 'readwrite' : 'readwrite-primary';\n\n try {\n if (!keepPersistedTargetData) {\n await localStoreImpl.persistence.runTransaction(\n 'Release target',\n mode,\n txn => {\n return localStoreImpl.persistence.referenceDelegate.removeTarget(\n txn,\n targetData!\n );\n }\n );\n }\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n logDebug(\n LOG_TAG,\n `Failed to update sequence numbers for target ${targetId}: ${e}`\n );\n } else {\n throw e;\n }\n }\n\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.remove(targetId);\n localStoreImpl.targetIdByTarget.delete(targetData!.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */\nexport function localStoreExecuteQuery(\n localStore: LocalStore,\n query: Query,\n usePreviousResults: boolean\n): Promise<QueryResult> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let lastLimboFreeSnapshotVersion = SnapshotVersion.min();\n let remoteKeys = documentKeySet();\n\n return localStoreImpl.persistence.runTransaction(\n 'Execute query',\n 'readwrite', // Use readwrite instead of readonly so indexes can be created\n txn => {\n return localStoreGetTargetData(localStoreImpl, txn, queryToTarget(query))\n .next(targetData => {\n if (targetData) {\n lastLimboFreeSnapshotVersion =\n targetData.lastLimboFreeSnapshotVersion;\n return localStoreImpl.targetCache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(result => {\n remoteKeys = result;\n });\n }\n })\n .next(() =>\n localStoreImpl.queryEngine.getDocumentsMatchingQuery(\n txn,\n query,\n usePreviousResults\n ? lastLimboFreeSnapshotVersion\n : SnapshotVersion.min(),\n usePreviousResults ? remoteKeys : documentKeySet()\n )\n )\n .next(documents => {\n setMaxReadTime(\n localStoreImpl,\n queryCollectionGroup(query),\n documents\n );\n return { documents, remoteKeys };\n });\n }\n );\n}\n\nfunction applyWriteToRemoteDocuments(\n localStoreImpl: LocalStoreImpl,\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(() => documentBuffer.getEntry(txn, docKey))\n .next(doc => {\n const ackVersion = batchResult.docVersions.get(docKey);\n hardAssert(\n ackVersion !== null,\n 'ackVersions should contain every doc in the write.'\n );\n if (doc.version.compareTo(ackVersion!) < 0) {\n batch.applyToRemoteDocument(doc, batchResult);\n if (doc.isValidDocument()) {\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n doc.setReadTime(batchResult.commitVersion);\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain.next(() =>\n localStoreImpl.mutationQueue.removeMutationBatch(txn, batch)\n );\n}\n\n/** Returns the local view of the documents affected by a mutation batch. */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreLookupMutationDocuments(\n localStore: LocalStore,\n batchId: BatchId\n): Promise<DocumentMap | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const mutationQueueImpl = debugCast(\n localStoreImpl.mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n return localStoreImpl.persistence.runTransaction(\n 'Lookup mutation documents',\n 'readonly',\n txn => {\n return mutationQueueImpl.lookupMutationKeys(txn, batchId).next(keys => {\n if (keys) {\n return localStoreImpl.localDocuments.getDocuments(\n txn,\n keys\n ) as PersistencePromise<DocumentMap | null>;\n } else {\n return PersistencePromise.resolve<DocumentMap | null>(null);\n }\n });\n }\n );\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreRemoveCachedMutationBatchMetadata(\n localStore: LocalStore,\n batchId: BatchId\n): void {\n const mutationQueueImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).mutationQueue,\n IndexedDbMutationQueue // We only support IndexedDb in multi-tab mode.\n );\n mutationQueueImpl.removeCachedMutationKeys(batchId);\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetActiveClients(\n localStore: LocalStore\n): Promise<ClientId[]> {\n const persistenceImpl = debugCast(\n debugCast(localStore, LocalStoreImpl).persistence,\n IndexedDbPersistence // We only support IndexedDb in multi-tab mode.\n );\n return persistenceImpl.getActiveClients();\n}\n\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetCachedTarget(\n localStore: LocalStore,\n targetId: TargetId\n): Promise<Target | null> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetCacheImpl = debugCast(\n localStoreImpl.targetCache,\n IndexedDbTargetCache // We only support IndexedDb in multi-tab mode.\n );\n const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetId);\n if (cachedTargetData) {\n return Promise.resolve(cachedTargetData.target);\n } else {\n return localStoreImpl.persistence.runTransaction(\n 'Get target data',\n 'readonly',\n txn => {\n return targetCacheImpl\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 that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nexport function localStoreGetNewDocumentChanges(\n localStore: LocalStore,\n collectionGroup: string\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n const readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n\n return localStoreImpl.persistence\n .runTransaction('Get new document changes', 'readonly', txn =>\n localStoreImpl.remoteDocuments.getAllFromCollectionGroup(\n txn,\n collectionGroup,\n newIndexOffsetSuccessorFromReadTime(readTime, INITIAL_LARGEST_BATCH_ID),\n /* limit= */ Number.MAX_SAFE_INTEGER\n )\n )\n .then(changedDocs => {\n setMaxReadTime(localStoreImpl, collectionGroup, changedDocs);\n return changedDocs;\n });\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction setMaxReadTime(\n localStoreImpl: LocalStoreImpl,\n collectionGroup: string,\n changedDocs: SortedMap<DocumentKey, Document>\n): void {\n let readTime =\n localStoreImpl.collectionGroupReadTime.get(collectionGroup) ||\n SnapshotVersion.min();\n changedDocs.forEach((_, doc) => {\n if (doc.readTime.compareTo(readTime) > 0) {\n readTime = doc.readTime;\n }\n });\n localStoreImpl.collectionGroupReadTime.set(collectionGroup, readTime);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\nfunction umbrellaTarget(bundleName: string): Target {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return queryToTarget(\n newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${bundleName}`))\n );\n}\n\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nexport async function localStoreApplyBundledDocuments(\n localStore: LocalStore,\n bundleConverter: BundleConverter,\n documents: BundledDocuments,\n bundleName: string\n): Promise<DocumentMap> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n let documentKeys = documentKeySet();\n let documentMap = mutableDocumentMap();\n for (const bundleDoc of documents) {\n const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name!);\n if (bundleDoc.document) {\n documentKeys = documentKeys.add(documentKey);\n }\n const doc = bundleConverter.toMutableDocument(bundleDoc);\n doc.setReadTime(\n bundleConverter.toSnapshotVersion(bundleDoc.metadata.readTime!)\n );\n documentMap = documentMap.insert(documentKey, doc);\n }\n\n const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n const umbrellaTargetData = await localStoreAllocateTarget(\n localStoreImpl,\n umbrellaTarget(bundleName)\n );\n return localStoreImpl.persistence.runTransaction(\n 'Apply bundle documents',\n 'readwrite',\n txn => {\n return populateDocumentChangeBuffer(txn, documentBuffer, documentMap)\n .next(documentChangeResult => {\n documentBuffer.apply(txn);\n return documentChangeResult;\n })\n .next(documentChangeResult => {\n return localStoreImpl.targetCache\n .removeMatchingKeysForTargetId(txn, umbrellaTargetData.targetId)\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n txn,\n documentKeys,\n umbrellaTargetData.targetId\n )\n )\n .next(() =>\n localStoreImpl.localDocuments.getLocalViewOfDocuments(\n txn,\n documentChangeResult.changedDocuments,\n documentChangeResult.existenceChangedKeys\n )\n )\n .next(() => documentChangeResult.changedDocuments);\n });\n }\n );\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\nexport function localStoreHasNewerBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise<boolean> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const currentReadTime = fromVersion(bundleMetadata.createTime!);\n return localStoreImpl.persistence\n .runTransaction('hasNewerBundle', 'readonly', transaction => {\n return localStoreImpl.bundleCache.getBundleMetadata(\n transaction,\n bundleMetadata.id!\n );\n })\n .then(cached => {\n return !!cached && cached.createTime!.compareTo(currentReadTime) >= 0;\n });\n}\n\n/**\n * Saves the given `BundleMetadata` to local persistence.\n */\nexport function localStoreSaveBundle(\n localStore: LocalStore,\n bundleMetadata: BundleMetadata\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save bundle',\n 'readwrite',\n transaction => {\n return localStoreImpl.bundleCache.saveBundleMetadata(\n transaction,\n bundleMetadata\n );\n }\n );\n}\n\n/**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */\nexport function localStoreGetNamedQuery(\n localStore: LocalStore,\n queryName: string\n): Promise<NamedQuery | undefined> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Get named query',\n 'readonly',\n transaction =>\n localStoreImpl.bundleCache.getNamedQuery(transaction, queryName)\n );\n}\n\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nexport async function localStoreSaveNamedQuery(\n localStore: LocalStore,\n query: ProtoNamedQuery,\n documents: DocumentKeySet = documentKeySet()\n): Promise<void> {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const allocated = await localStoreAllocateTarget(\n localStore,\n queryToTarget(fromBundledQuery(query.bundledQuery!))\n );\n\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n return localStoreImpl.persistence.runTransaction(\n 'Save named query',\n 'readwrite',\n transaction => {\n const readTime = fromVersion(query.readTime!);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (allocated.snapshotVersion.compareTo(readTime) >= 0) {\n return localStoreImpl.bundleCache.saveNamedQuery(transaction, query);\n }\n\n // Update existing target data because the query from the bundle is newer.\n const newTargetData = allocated.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n readTime\n );\n localStoreImpl.targetDataByTarget =\n localStoreImpl.targetDataByTarget.insert(\n newTargetData.targetId,\n newTargetData\n );\n return localStoreImpl.targetCache\n .updateTargetData(transaction, newTargetData)\n .next(() =>\n localStoreImpl.targetCache.removeMatchingKeysForTargetId(\n transaction,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.targetCache.addMatchingKeys(\n transaction,\n documents,\n allocated.targetId\n )\n )\n .next(() =>\n localStoreImpl.bundleCache.saveNamedQuery(transaction, query)\n );\n }\n );\n}\n\nexport async function localStoreConfigureFieldIndexes(\n localStore: LocalStore,\n newFieldIndexes: FieldIndex[]\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n const promises: Array<PersistencePromise<void>> = [];\n return localStoreImpl.persistence.runTransaction(\n 'Configure indexes',\n 'readwrite',\n transaction =>\n indexManager\n .getFieldIndexes(transaction)\n .next(oldFieldIndexes =>\n diffArrays(\n oldFieldIndexes,\n newFieldIndexes,\n fieldIndexSemanticComparator,\n fieldIndex => {\n promises.push(\n indexManager.addFieldIndex(transaction, fieldIndex)\n );\n },\n fieldIndex => {\n promises.push(\n indexManager.deleteFieldIndex(transaction, fieldIndex)\n );\n }\n )\n )\n .next(() => PersistencePromise.waitFor(promises))\n );\n}\n\nexport function localStoreSetIndexAutoCreationEnabled(\n localStore: LocalStore,\n isEnabled: boolean\n): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n localStoreImpl.queryEngine.indexAutoCreationEnabled = isEnabled;\n}\n\nexport function localStoreDeleteAllFieldIndexes(\n localStore: LocalStore\n): Promise<void> {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n return localStoreImpl.persistence.runTransaction(\n 'Delete All Indexes',\n 'readwrite',\n transaction => indexManager.deleteAllFieldIndexes(transaction)\n );\n}\n\n/**\n * Test-only hooks into the SDK for use exclusively by tests.\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('creating instances is not supported');\n }\n\n static setIndexAutoCreationSettings(\n localStore: LocalStore,\n settings: {\n indexAutoCreationMinCollectionSize?: number;\n relativeIndexReadCostPerDocument?: number;\n }\n ): void {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n if (settings.indexAutoCreationMinCollectionSize !== undefined) {\n localStoreImpl.queryEngine.indexAutoCreationMinCollectionSize =\n settings.indexAutoCreationMinCollectionSize;\n }\n if (settings.relativeIndexReadCostPerDocument !== undefined) {\n localStoreImpl.queryEngine.relativeIndexReadCostPerDocument =\n settings.relativeIndexReadCostPerDocument;\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\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 debugAssert(\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// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n// firestore_bundle_loaded_v2_<persistenceKey>\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n return `${BUNDLE_LOADED_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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\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';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\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 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 * Notifies other clients when remote documents have changed due to loading\n * a bundle.\n *\n * @param collectionGroups The collection groups affected by this bundle.\n */\n notifyBundleLoaded(collectionGroups: Set<string>): 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 debugAssert(\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 logError(\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 debugAssert(\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 logError(\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 logError(\n LOG_TAG,\n `Failed to parse client data for instance '${clientId}': ${value}`\n );\n return null;\n }\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */\nexport class SharedOnlineState {\n constructor(readonly clientId: string, readonly onlineState: OnlineState) {}\n\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(value: string): SharedOnlineState | null {\n const onlineState = JSON.parse(value) as SharedOnlineStateSchema;\n\n const validData =\n typeof onlineState === 'object' &&\n ['Unknown', 'Online', 'Offline'].indexOf(onlineState.onlineState) !==\n -1 &&\n typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(\n onlineState.clientId,\n onlineState.onlineState as OnlineState\n );\n } else {\n logError(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 storageListener = this.handleWebStorageEvent.bind(this);\n private readonly onlineStateKey: string;\n private readonly bundleLoadedKey: string;\n private readonly clientStateKeyRe: RegExp;\n private readonly mutationBatchKeyRe: RegExp;\n private readonly queryTargetKeyRe: RegExp;\n private activeClients = new SortedMap<string, ClientState>(\n primitiveComparator\n );\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 window: WindowLike,\n private readonly queue: AsyncQueue,\n private readonly persistenceKey: string,\n private readonly localClientId: ClientId,\n initialUser: User\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.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.activeClients.insert(\n this.localClientId,\n new LocalClientState()\n );\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 this.bundleLoadedKey = createBundleLoadedKey(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.window.addEventListener('storage', this.storageListener);\n }\n\n /** Returns 'true' if WebStorage is available in the current environment. */\n static isAvailable(window: WindowLike | null): window is WindowLike {\n return !!(window && window.localStorage);\n }\n\n async start(): Promise<void> {\n debugAssert(!this.started, 'WebStorageSharedClientState already started');\n debugAssert(\n this.syncEngine !== null,\n 'syncEngine property must be set before calling start()'\n );\n debugAssert(\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 = this.activeClients.insert(\n clientState.clientId,\n clientState\n );\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.window.addEventListener('pagehide', () => 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 return this.extractActiveQueryTargets(this.activeClients);\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n let found = false;\n this.activeClients.forEach((key, value) => {\n if (value.activeTargetIds.has(targetId)) {\n found = true;\n }\n });\n return found;\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 notifyBundleLoaded(collectionGroups: Set<string>): void {\n this.persistBundleLoadedState(collectionGroups);\n }\n\n shutdown(): void {\n if (this.started) {\n this.window.removeEventListener('storage', this.storageListener);\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 logDebug(LOG_TAG, 'READ', key, value);\n return value;\n }\n\n private setItem(key: string, value: string): void {\n logDebug(LOG_TAG, 'SET', key, value);\n this.storage.setItem(key, value);\n }\n\n private removeItem(key: string): void {\n logDebug(LOG_TAG, 'REMOVE', key);\n this.storage.removeItem(key);\n }\n\n private handleWebStorageEvent(event: Event): void {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const storageEvent = event as StorageEvent;\n if (storageEvent.storageArea === this.storage) {\n logDebug(LOG_TAG, 'EVENT', storageEvent.key, storageEvent.newValue);\n\n if (storageEvent.key === this.localClientStorageKey) {\n logError(\n 'Received WebStorage notification for local change. Another client might have ' +\n 'garbage-collected our state'\n );\n return;\n }\n\n this.queue.enqueueRetryable(async () => {\n if (!this.started) {\n this.earlyEvents.push(storageEvent);\n return;\n }\n\n if (storageEvent.key === null) {\n return;\n }\n\n if (this.clientStateKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue != null) {\n const clientState = this.fromWebStorageClientState(\n storageEvent.key,\n storageEvent.newValue\n );\n if (clientState) {\n return this.handleClientStateEvent(\n clientState.clientId,\n clientState\n );\n }\n } else {\n const clientId = this.fromWebStorageClientStateKey(\n storageEvent.key\n )!;\n return this.handleClientStateEvent(clientId, null);\n }\n } else if (this.mutationBatchKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const mutationMetadata = this.fromWebStorageMutationMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (mutationMetadata) {\n return this.handleMutationBatchEvent(mutationMetadata);\n }\n }\n } else if (this.queryTargetKeyRe.test(storageEvent.key)) {\n if (storageEvent.newValue !== null) {\n const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(\n storageEvent.key,\n storageEvent.newValue\n );\n if (queryTargetMetadata) {\n return this.handleQueryTargetEvent(queryTargetMetadata);\n }\n }\n } else if (storageEvent.key === this.onlineStateKey) {\n if (storageEvent.newValue !== null) {\n const onlineState = this.fromWebStorageOnlineState(\n storageEvent.newValue\n );\n if (onlineState) {\n return this.handleOnlineStateEvent(onlineState);\n }\n }\n } else if (storageEvent.key === this.sequenceNumberKey) {\n debugAssert(\n !!this.sequenceNumberHandler,\n 'Missing sequenceNumberHandler'\n );\n const sequenceNumber = fromWebStorageSequenceNumber(\n storageEvent.newValue\n );\n if (sequenceNumber !== ListenSequence.INVALID) {\n this.sequenceNumberHandler!(sequenceNumber);\n }\n } else if (storageEvent.key === this.bundleLoadedKey) {\n const collectionGroups = this.fromWebStoreBundleLoadedState(\n storageEvent.newValue!\n );\n await Promise.all(\n collectionGroups.map(cg =>\n this.syncEngine!.synchronizeWithChangedDocuments(cg)\n )\n );\n }\n });\n }\n }\n\n private get localClientState(): LocalClientState {\n return this.activeClients.get(this.localClientId) as LocalClientState;\n }\n\n private persistClientState(): void {\n this.setItem(\n this.localClientStorageKey,\n this.localClientState.toWebStorageJSON()\n );\n }\n\n private persistMutationState(\n batchId: BatchId,\n state: MutationBatchState,\n error?: FirestoreError\n ): void {\n const mutationState = new MutationMetadata(\n this.currentUser,\n batchId,\n state,\n error\n );\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\n }\n\n private removeMutationState(batchId: BatchId): void {\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.removeItem(mutationKey);\n }\n\n private persistOnlineState(onlineState: OnlineState): void {\n const entry: SharedOnlineStateSchema = {\n clientId: this.localClientId,\n onlineState\n };\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n }\n\n private persistQueryTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n const targetKey = createWebStorageQueryTargetMetadataKey(\n this.persistenceKey,\n targetId\n );\n const targetMetadata = new QueryTargetMetadata(targetId, state, error);\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n }\n\n private persistBundleLoadedState(collectionGroups: Set<string>): void {\n const json = JSON.stringify(Array.from(collectionGroups));\n this.setItem(this.bundleLoadedKey, json);\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 debugAssert(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 debugAssert(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 debugAssert(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 fromWebStoreBundleLoadedState(value: string): string[] {\n return JSON.parse(value) as string[];\n }\n\n private async handleMutationBatchEvent(\n mutationBatch: MutationMetadata\n ): Promise<void> {\n if (mutationBatch.user.uid !== this.currentUser.uid) {\n logDebug(\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 updatedClients = clientState\n ? this.activeClients.insert(clientId, clientState)\n : this.activeClients.remove(clientId);\n\n const existingTargets = this.extractActiveQueryTargets(this.activeClients);\n const newTargets = this.extractActiveQueryTargets(updatedClients);\n\n const addedTargets: TargetId[] = [];\n const removedTargets: TargetId[] = [];\n\n newTargets.forEach(targetId => {\n if (!existingTargets.has(targetId)) {\n addedTargets.push(targetId);\n }\n });\n\n existingTargets.forEach(targetId => {\n if (!newTargets.has(targetId)) {\n removedTargets.push(targetId);\n }\n });\n\n return this.syncEngine!.applyActiveTargetsChange(\n addedTargets,\n removedTargets\n ).then(() => {\n this.activeClients = updatedClients;\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.get(onlineState.clientId)) {\n this.onlineStateHandler!(onlineState.onlineState);\n }\n }\n\n private extractActiveQueryTargets(\n clients: SortedMap<string, ClientState>\n ): SortedSet<TargetId> {\n let activeTargets = targetIdSet();\n clients.forEach((kev, value) => {\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\n });\n return activeTargets;\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 hardAssert(\n typeof parsed === 'number',\n 'Found non-numeric sequence number'\n );\n sequenceNumber = parsed;\n } catch (e) {\n logError(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 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 notifyBundleLoaded(collectionGroups: Set<string>): void {\n // No op.\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ConnectivityMonitor,\n ConnectivityMonitorCallback,\n NetworkStatus\n} from '../../remote/connectivity_monitor';\nimport { logDebug } from '../../util/log';\n\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\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 logDebug(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 logDebug(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 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The value returned from the most recent invocation of\n * `generateUniqueDebugId()`, or null if it has never been invoked.\n */\nlet lastUniqueDebugId: number | null = null;\n\n/**\n * Generates and returns an initial value for `lastUniqueDebugId`.\n *\n * The returned value is randomly selected from a range of integers that are\n * represented as 8 hexadecimal digits. This means that (within reason) any\n * numbers generated by incrementing the returned number by 1 will also be\n * represented by 8 hexadecimal digits. This leads to all \"IDs\" having the same\n * length when converted to a hexadecimal string, making reading logs containing\n * these IDs easier to follow. And since the return value is randomly selected\n * it will help to differentiate between logs from different executions.\n */\nfunction generateInitialUniqueDebugId(): number {\n const minResult = 0x10000000;\n const maxResult = 0x90000000;\n const resultRange = maxResult - minResult;\n const resultOffset = Math.round(resultRange * Math.random());\n return minResult + resultOffset;\n}\n\n/**\n * Generates and returns a unique ID as a hexadecimal string.\n *\n * The returned ID is intended to be used in debug logging messages to help\n * correlate log messages that may be spatially separated in the logs, but\n * logically related. For example, a network connection could include the same\n * \"debug ID\" string in all of its log messages to help trace a specific\n * connection over time.\n *\n * @return the 10-character generated ID (e.g. \"0xa1b2c3d4\").\n */\nexport function generateUniqueDebugId(): string {\n if (lastUniqueDebugId === null) {\n lastUniqueDebugId = generateInitialUniqueDebugId();\n } else {\n lastUniqueDebugId++;\n }\n return '0x' + lastUniqueDebugId.toString(16);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '../../src/core/version';\nimport { Token } from '../api/credentials';\nimport {\n DatabaseId,\n DatabaseInfo,\n DEFAULT_DATABASE_NAME\n} from '../core/database_info';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { generateUniqueDebugId } from '../util/debug_uid';\nimport { FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { StringMap } from '../util/types';\n\nimport { Connection, Stream } from './connection';\n\nconst LOG_TAG = 'RestConnection';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\nconst RPC_NAME_URL_MAPPING: StringMap = {};\n\nRPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_URL_MAPPING['Commit'] = 'commit';\nRPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';\nRPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';\n\nconst RPC_URL_VERSION = 'v1';\n\n// SDK_VERSION is updated to different value at runtime depending on the entry point,\n// so we need to get its value when we need it in a function.\nfunction getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nexport abstract class RestConnection implements Connection {\n protected readonly databaseId: DatabaseId;\n protected readonly baseUrl: string;\n private readonly databasePath: string;\n private readonly requestParams: string;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return false;\n }\n\n constructor(private readonly databaseInfo: DatabaseInfo) {\n this.databaseId = databaseInfo.databaseId;\n const proto = databaseInfo.ssl ? 'https' : 'http';\n const projectId = encodeURIComponent(this.databaseId.projectId);\n const databaseId = encodeURIComponent(this.databaseId.database);\n this.baseUrl = proto + '://' + databaseInfo.host;\n this.databasePath = `projects/${projectId}/databases/${databaseId}`;\n this.requestParams =\n this.databaseId.database === DEFAULT_DATABASE_NAME\n ? `project_id=${projectId}`\n : `project_id=${projectId}&database_id=${databaseId}`;\n }\n\n invokeRPC<Req, Resp>(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise<Resp> {\n const streamId = generateUniqueDebugId();\n const url = this.makeUrl(rpcName, path.toUriEncodedString());\n logDebug(LOG_TAG, `Sending RPC '${rpcName}' ${streamId}:`, url, req);\n\n const headers: StringMap = {\n 'google-cloud-resource-prefix': this.databasePath,\n 'x-goog-request-params': this.requestParams\n };\n this.modifyHeadersForRequest(headers, authToken, appCheckToken);\n\n return this.performRPCRequest<Req, Resp>(rpcName, url, headers, req).then(\n response => {\n logDebug(LOG_TAG, `Received RPC '${rpcName}' ${streamId}: `, response);\n return response;\n },\n (err: FirestoreError) => {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error: `,\n err,\n 'url: ',\n url,\n 'request:',\n req\n );\n throw err;\n }\n );\n }\n\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\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[]>(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream<Req, Resp>(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<Req, Resp>;\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 protected modifyHeadersForRequest(\n headers: StringMap,\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n headers['X-Goog-Api-Client'] = getGoogApiClientValue();\n\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n headers['Content-Type'] = 'text/plain';\n\n if (this.databaseInfo.appId) {\n headers['X-Firebase-GMPID'] = this.databaseInfo.appId;\n }\n\n if (authToken) {\n authToken.headers.forEach((value, key) => (headers[key] = value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => (headers[key] = value));\n }\n }\n\n /**\n * Performs an RPC request using an implementation specific networking layer.\n */\n protected abstract performRPCRequest<Req, Resp>(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise<Resp>;\n\n private makeUrl(rpcName: string, path: string): string {\n const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];\n debugAssert(\n urlRpcName !== undefined,\n 'Unknown REST mapping for: ' + rpcName\n );\n return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;\n }\n\n /**\n * Closes and cleans up any resources associated with the connection. This\n * implementation is a no-op because there are no resources associated\n * with the RestConnection that need to be cleaned up.\n */\n terminate(): void {\n // No-op\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } 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 debugAssert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n }\n\n onClose(callback: (err?: FirestoreError) => void): void {\n debugAssert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n }\n\n onMessage(callback: (msg: O) => void): void {\n debugAssert(!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 debugAssert(\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 debugAssert(\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 debugAssert(\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createWebChannelTransport,\n ErrorCode,\n EventType,\n WebChannel,\n WebChannelError,\n WebChannelOptions,\n XhrIo,\n getStatEventTarget,\n EventTarget,\n StatEvent,\n Event,\n Stat\n} from '@firebase/webchannel-wrapper';\n\nimport { Token } from '../../api/credentials';\nimport { ExperimentalLongPollingOptions } from '../../api/long_polling_options';\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport {\n mapCodeFromRpcStatus,\n mapCodeFromHttpResponseErrorStatus\n} from '../../remote/rpc_error';\nimport { StreamBridge } from '../../remote/stream_bridge';\nimport { fail, hardAssert } from '../../util/assert';\nimport { generateUniqueDebugId } from '../../util/debug_uid';\nimport { Code, FirestoreError } from '../../util/error';\nimport { logDebug, logWarn } from '../../util/log';\nimport { Rejecter, Resolver } from '../../util/promise';\nimport { StringMap } from '../../util/types';\n\nconst LOG_TAG = 'WebChannelConnection';\n\nconst RPC_STREAM_SERVICE = 'google.firestore.v1.Firestore';\n\nconst XHR_TIMEOUT_SECS = 15;\n\nexport class WebChannelConnection extends RestConnection {\n private readonly forceLongPolling: boolean;\n private readonly autoDetectLongPolling: boolean;\n private readonly useFetchStreams: boolean;\n private readonly longPollingOptions: ExperimentalLongPollingOptions;\n\n constructor(info: DatabaseInfo) {\n super(info);\n this.forceLongPolling = info.forceLongPolling;\n this.autoDetectLongPolling = info.autoDetectLongPolling;\n this.useFetchStreams = info.useFetchStreams;\n this.longPollingOptions = info.longPollingOptions;\n }\n\n protected performRPCRequest<Req, Resp>(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise<Resp> {\n const streamId = generateUniqueDebugId();\n return new Promise((resolve: Resolver<Resp>, reject: Rejecter) => {\n const xhr = new XhrIo();\n xhr.setWithCredentials(true);\n xhr.listenOnce(EventType.COMPLETE, () => {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const json = xhr.getResponseJson() as Resp;\n logDebug(\n LOG_TAG,\n `XHR for RPC '${rpcName}' ${streamId} received:`,\n JSON.stringify(json)\n );\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} 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 logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with status:`,\n status,\n 'response text:',\n xhr.getResponseText()\n );\n if (status > 0) {\n let response = xhr.getResponseJson();\n if (Array.isArray(response)) {\n response = response[0];\n }\n const responseError = (response as WebChannelError)?.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 reject(\n new FirestoreError(Code.UNAVAILABLE, 'Connection failed.')\n );\n }\n break;\n default:\n fail(\n `RPC '${rpcName}' ${streamId} ` +\n 'failed with unanticipated webchannel error: ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.'\n );\n }\n } finally {\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} completed.`);\n }\n });\n\n const requestString = JSON.stringify(body);\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} sending request:`, body);\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n }\n\n openStream<Req, Resp>(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<Req, Resp> {\n const streamId = generateUniqueDebugId();\n const urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n const webchannelTransport = createWebChannelTransport();\n const requestStats = getStatEventTarget();\n const request: WebChannelOptions = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: true,\n supportsCrossDomainXhr: true,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 10 * 60 * 1000\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n };\n\n const longPollingTimeoutSeconds = this.longPollingOptions.timeoutSeconds;\n if (longPollingTimeoutSeconds !== undefined) {\n request.longPollingTimeout = Math.round(longPollingTimeoutSeconds * 1000);\n }\n\n if (this.useFetchStreams) {\n request.useFetchStreams = true;\n }\n\n this.modifyHeadersForRequest(\n request.initMessageHeaders!,\n authToken,\n appCheckToken\n );\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 encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n request.encodeInitMessageHeaders = true;\n\n const url = urlParts.join('');\n logDebug(\n LOG_TAG,\n `Creating RPC '${rpcName}' stream ${streamId}: ${url}`,\n request\n );\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 logDebug(\n LOG_TAG,\n `Opening RPC '${rpcName}' stream ${streamId} transport.`\n );\n channel.open();\n opened = true;\n }\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} sending:`,\n msg\n );\n channel.send(msg);\n } else {\n logDebug(\n LOG_TAG,\n `Not sending because RPC '${rpcName}' stream ${streamId} ` +\n 'is closed:',\n msg\n );\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 target: EventTarget,\n type: string | number,\n fn: (param: T) => void\n ): void => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n target.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(channel, WebChannel.EventType.OPEN, () => {\n if (!closed) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport opened.`\n );\n }\n });\n\n unguardedEventListen(channel, WebChannel.EventType.CLOSE, () => {\n if (!closed) {\n closed = true;\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport closed`\n );\n streamBridge.callOnClose();\n }\n });\n\n unguardedEventListen<Error>(channel, WebChannel.EventType.ERROR, err => {\n if (!closed) {\n closed = true;\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} transport errored:`,\n err\n );\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 channel,\n WebChannel.EventType.MESSAGE,\n msg => {\n if (!closed) {\n const msgData = msg.data[0];\n hardAssert(!!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 logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received error:`,\n error\n );\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 logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} received:`,\n msgData\n );\n streamBridge.callOnMessage(msgData);\n }\n }\n }\n );\n\n unguardedEventListen<StatEvent>(requestStats, Event.STAT_EVENT, event => {\n if (event.stat === Stat.PROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected buffering proxy`\n );\n } else if (event.stat === Stat.NOPROXY) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} detected no buffering proxy`\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","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Default factory for <code>WebChannelTransport</code> to\n * avoid exposing concrete classes to clients.\n */\n\ngoog.provide('goog.net.createWebChannelTransport');\n\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\ngoog.requireType('goog.net.WebChannelTransport');\n\n\n/**\n * Create a new WebChannelTransport instance using the default implementation.\n * Throws an error message if no default transport available in the current\n * environment.\n *\n * @return {!goog.net.WebChannelTransport} the newly created transport instance.\n */\ngoog.net.createWebChannelTransport = function() {\n 'use strict';\n return new goog.labs.net.webChannel.WebChannelBaseTransport();\n};\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The Platform's 'window' implementation or null if not available. */\nexport function getWindow(): Window | null {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return typeof document !== 'undefined' ? document : null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Return the Platform-specific serializer monitor. */\nimport { DatabaseId } from '../../core/database_info';\nimport { JsonProtoSerializer } from '../../remote/serializer';\n\nexport function newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\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: DelayedOperation<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 (remainingDelayMs > 0) {\n logDebug(\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 skipBackoff(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.skipDelay();\n this.timerPromise = null;\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider, Token } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetData } from '../local/target_data';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport {\n ListenRequest as ProtoListenRequest,\n ListenResponse as ProtoListenResponse,\n WriteRequest as ProtoWriteRequest,\n WriteResponse as ProtoWriteResponse\n} from '../protos/firestore_proto_api';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { ExponentialBackoff } from './backoff';\nimport { Connection, Stream } from './connection';\nimport {\n fromVersion,\n fromWatchChange,\n fromWriteResults,\n getEncodedDatabaseId,\n JsonProtoSerializer,\n toListenRequestLabels,\n toMutation,\n toTarget,\n versionFromListenResponse\n} from './serializer';\nimport { WatchChange } from './watch_change';\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 ProtoListenRequest {\n database?: string;\n}\nexport interface WriteRequest extends ProtoWriteRequest {\n database?: string;\n}\n/**\n * PersistentStream can be in one of 5 states (each described in detail below)\n * based on the following state transition diagram:\n *\n * start() called auth & connection succeeded\n * INITIAL ----------------> STARTING -----------------------------> OPEN\n * ^ | |\n * | | error occurred |\n * | \\-----------------------------v-----/\n * | |\n * backoff | |\n * elapsed | start() called |\n * \\--- BACKOFF <---------------- ERROR\n *\n * [any state] --------------------------> INITIAL\n * stop() called or\n * idle timer expired\n */\nconst enum PersistentStreamState {\n /**\n * The streaming RPC is not yet running and there's no error condition.\n * Calling start() will start the stream immediately without backoff.\n * While in this state isStarted() will return false.\n */\n Initial,\n\n /**\n * The stream is starting, either waiting for an auth token or for the stream\n * to successfully open. While in this state, isStarted() will return true but\n * isOpen() will return false.\n */\n Starting,\n\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted() and isOpen() will return true.\n */\n Open,\n\n /**\n * The stream is healthy and has been connected for more than 10 seconds. We\n * therefore assume that the credentials we passed were valid. Both\n * isStarted() and isOpen() will return true.\n */\n Healthy,\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/** The time a stream stays open until we consider it healthy. */\nconst HEALTHY_TIMEOUT_MS = 10 * 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: DelayedOperation<void> | null = null;\n private healthCheck: DelayedOperation<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 private healthTimerId: TimerId,\n protected connection: Connection,\n private authCredentialsProvider: CredentialsProvider<User>,\n private appCheckCredentialsProvider: CredentialsProvider<string>,\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.Backoff ||\n this.isOpen()\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 (\n this.state === PersistentStreamState.Open ||\n this.state === PersistentStreamState.Healthy\n );\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 debugAssert(\n this.state === PersistentStreamState.Initial,\n 'Already started'\n );\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 debugAssert(\n !this.isStarted(),\n 'Can only inhibit backoff in a stopped state'\n );\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 /** Cancels the health check delayed operation. */\n private cancelHealthCheck(): void {\n if (this.healthCheck) {\n this.healthCheck.cancel();\n this.healthCheck = 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 debugAssert(this.isStarted(), 'Only started streams should be closed.');\n debugAssert(\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.cancelHealthCheck();\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 logError(error.toString());\n logError(\n 'Using maximum backoff delay to prevent overloading the backend.'\n );\n this.backoff.resetToMax();\n } else if (\n error &&\n error.code === Code.UNAUTHENTICATED &&\n this.state !== PersistentStreamState.Healthy\n ) {\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken();\n this.appCheckCredentialsProvider.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 authToken: Token | null,\n appCheckToken: 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 debugAssert(\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 Promise.all([\n this.authCredentialsProvider.getToken(),\n this.appCheckCredentialsProvider.getToken()\n ]).then(\n ([authToken, appCheckToken]) => {\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(authToken, appCheckToken);\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(\n authToken: Token | null,\n appCheckToken: Token | null\n ): void {\n debugAssert(\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(authToken, appCheckToken);\n this.stream.onOpen(() => {\n dispatchIfNotClosed(() => {\n debugAssert(\n this.state === PersistentStreamState.Starting,\n 'Expected stream to be in state Starting, but was ' + this.state\n );\n this.state = PersistentStreamState.Open;\n debugAssert(\n this.healthCheck === null,\n 'Expected healthCheck to be null'\n );\n this.healthCheck = this.queue.enqueueAfterDelay(\n this.healthTimerId,\n HEALTHY_TIMEOUT_MS,\n () => {\n if (this.isOpen()) {\n this.state = PersistentStreamState.Healthy;\n }\n return Promise.resolve();\n }\n );\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 debugAssert(\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 debugAssert(\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 debugAssert(this.isStarted(), 'PersistentStream should have started');\n });\n }\n\n // Visible for tests\n handleStreamClose(error?: FirestoreError): Promise<void> {\n debugAssert(\n this.isStarted(),\n \"Can't handle server close on non-started stream\"\n );\n logDebug(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 logDebug(\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 ProtoListenRequest,\n ProtoListenResponse,\n WatchStreamListener\n> {\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n private serializer: JsonProtoSerializer,\n listener: WatchStreamListener\n ) {\n super(\n queue,\n TimerId.ListenStreamConnectionBackoff,\n TimerId.ListenStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\n listener\n );\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<ProtoListenRequest, ProtoListenResponse> {\n return this.connection.openStream<ProtoListenRequest, ProtoListenResponse>(\n 'Listen',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(watchChangeProto: ProtoListenResponse): Promise<void> {\n // A successful response means the stream is healthy\n this.backoff.reset();\n\n const watchChange = fromWatchChange(this.serializer, watchChangeProto);\n const snapshot = versionFromListenResponse(watchChangeProto);\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 = getEncodedDatabaseId(this.serializer);\n request.addTarget = toTarget(this.serializer, targetData);\n\n const labels = toListenRequestLabels(this.serializer, 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 = getEncodedDatabaseId(this.serializer);\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 ProtoWriteRequest,\n ProtoWriteResponse,\n WriteStreamListener\n> {\n private handshakeComplete_ = false;\n\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n private serializer: JsonProtoSerializer,\n listener: WriteStreamListener\n ) {\n super(\n queue,\n TimerId.WriteStreamConnectionBackoff,\n TimerId.WriteStreamIdle,\n TimerId.HealthCheckTimeout,\n connection,\n authCredentials,\n appCheckCredentials,\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 private lastStreamToken: string | Uint8Array | undefined;\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 this.lastStreamToken = undefined;\n super.start();\n }\n\n protected tearDown(): void {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n }\n\n protected startRpc(\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream<ProtoWriteRequest, ProtoWriteResponse> {\n return this.connection.openStream<ProtoWriteRequest, ProtoWriteResponse>(\n 'Write',\n authToken,\n appCheckToken\n );\n }\n\n protected onMessage(responseProto: ProtoWriteResponse): Promise<void> {\n // Always capture the last stream token.\n hardAssert(\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 hardAssert(\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 = fromWriteResults(\n responseProto.writeResults,\n responseProto.commitTime\n );\n const commitVersion = fromVersion(responseProto.commitTime!);\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 debugAssert(this.isOpen(), 'Writing handshake requires an opened stream');\n debugAssert(!this.handshakeComplete_, 'Handshake already completed');\n debugAssert(\n !this.lastStreamToken,\n 'Stream token should be empty during handshake'\n );\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 = getEncodedDatabaseId(this.serializer);\n this.sendRequest(request);\n }\n\n /** Sends a group of mutations to the Firestore backend to apply. */\n writeMutations(mutations: Mutation[]): void {\n debugAssert(this.isOpen(), 'Writing mutations requires an opened stream');\n debugAssert(\n this.handshakeComplete_,\n 'Handshake must be complete before writing mutations'\n );\n debugAssert(\n !!this.lastStreamToken,\n 'Trying to write mutation without a token'\n );\n\n const request: WriteRequest = {\n streamToken: this.lastStreamToken,\n writes: mutations.map(mutation => toMutation(this.serializer, mutation))\n };\n\n this.sendRequest(request);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { Aggregate } from '../core/aggregate';\nimport { DatabaseId } from '../core/database_info';\nimport { queryToAggregateTarget, Query, queryToTarget } from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { ResourcePath } from '../model/path';\nimport {\n ApiClientObjectMap,\n BatchGetDocumentsRequest as ProtoBatchGetDocumentsRequest,\n BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse,\n RunAggregationQueryRequest as ProtoRunAggregationQueryRequest,\n RunAggregationQueryResponse as ProtoRunAggregationQueryResponse,\n RunQueryRequest as ProtoRunQueryRequest,\n RunQueryResponse as ProtoRunQueryResponse,\n Value\n} from '../protos/firestore_proto_api';\nimport { debugAssert, debugCast, hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Connection } from './connection';\nimport {\n PersistentListenStream,\n PersistentWriteStream,\n WatchStreamListener,\n WriteStreamListener\n} from './persistent_stream';\nimport {\n fromDocument,\n fromBatchGetDocumentsResponse,\n JsonProtoSerializer,\n toMutation,\n toName,\n toQueryTarget,\n toResourcePath,\n toRunAggregationQueryRequest\n} from './serializer';\n\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\nexport abstract class Datastore {\n abstract terminate(): void;\n abstract serializer: JsonProtoSerializer;\n}\n\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass DatastoreImpl extends Datastore {\n terminated = false;\n\n constructor(\n readonly authCredentials: CredentialsProvider<User>,\n readonly appCheckCredentials: CredentialsProvider<string>,\n readonly connection: Connection,\n readonly serializer: JsonProtoSerializer\n ) {\n super();\n }\n\n verifyInitialized(): void {\n debugAssert(!!this.connection, 'Datastore.start() not called');\n if (this.terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /** Invokes the provided RPC with auth and AppCheck tokens. */\n invokeRPC<Req, Resp>(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise<Resp> {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeRPC<Req, Resp>(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise<Resp[]> {\n this.verifyInitialized();\n return Promise.all([\n this.authCredentials.getToken(),\n this.appCheckCredentials.getToken()\n ])\n .then(([authToken, appCheckToken]) => {\n return this.connection.invokeStreamingRPC<Req, Resp>(\n rpcName,\n toResourcePath(databaseId, resourcePath),\n request,\n authToken,\n appCheckToken,\n expectedResponseCount\n );\n })\n .catch((error: FirestoreError) => {\n if (error.name === 'FirebaseError') {\n if (error.code === Code.UNAUTHENTICATED) {\n this.authCredentials.invalidateToken();\n this.appCheckCredentials.invalidateToken();\n }\n throw error;\n } else {\n throw new FirestoreError(Code.UNKNOWN, error.toString());\n }\n });\n }\n\n terminate(): void {\n this.terminated = true;\n this.connection.terminate();\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nexport function newDatastore(\n authCredentials: CredentialsProvider<User>,\n appCheckCredentials: CredentialsProvider<string>,\n connection: Connection,\n serializer: JsonProtoSerializer\n): Datastore {\n return new DatastoreImpl(\n authCredentials,\n appCheckCredentials,\n connection,\n serializer\n );\n}\n\nexport async function invokeCommitRpc(\n datastore: Datastore,\n mutations: Mutation[]\n): Promise<void> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))\n };\n await datastoreImpl.invokeRPC(\n 'Commit',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request\n );\n}\n\nexport async function invokeBatchGetDocumentsRpc(\n datastore: Datastore,\n keys: DocumentKey[]\n): Promise<Document[]> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const request = {\n documents: keys.map(k => toName(datastoreImpl.serializer, k))\n };\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoBatchGetDocumentsRequest,\n ProtoBatchGetDocumentsResponse\n >(\n 'BatchGetDocuments',\n datastoreImpl.serializer.databaseId,\n ResourcePath.emptyPath(),\n request,\n keys.length\n );\n\n const docs = new Map<string, Document>();\n response.forEach(proto => {\n const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);\n docs.set(doc.key.toString(), doc);\n });\n const result: Document[] = [];\n keys.forEach(key => {\n const doc = docs.get(key.toString());\n hardAssert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n}\n\nexport async function invokeRunQueryRpc(\n datastore: Datastore,\n query: Query\n): Promise<Document[]> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { queryTarget, parent } = toQueryTarget(\n datastoreImpl.serializer,\n queryToTarget(query)\n );\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunQueryRequest,\n ProtoRunQueryResponse\n >('RunQuery', datastoreImpl.serializer.databaseId, parent, {\n structuredQuery: queryTarget.structuredQuery\n });\n return (\n response\n // Omit RunQueryResponses that only contain readTimes.\n .filter(proto => !!proto.document)\n .map(proto =>\n fromDocument(datastoreImpl.serializer, proto.document!, undefined)\n )\n );\n}\n\nexport async function invokeRunAggregationQueryRpc(\n datastore: Datastore,\n query: Query,\n aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n const { request, aliasMap, parent } = toRunAggregationQueryRequest(\n datastoreImpl.serializer,\n queryToAggregateTarget(query),\n aggregates\n );\n\n if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {\n delete request.parent;\n }\n const response = await datastoreImpl.invokeStreamingRPC<\n ProtoRunAggregationQueryRequest,\n ProtoRunAggregationQueryResponse\n >(\n 'RunAggregationQuery',\n datastoreImpl.serializer.databaseId,\n parent,\n request,\n /*expectedResponseCount=*/ 1\n );\n\n // Omit RunAggregationQueryResponse that only contain readTimes.\n const filteredResult = response.filter(proto => !!proto.result);\n\n hardAssert(\n filteredResult.length === 1,\n 'Aggregation fields are missing from result.'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result),\n 'aggregationQueryResponse.result'\n );\n debugAssert(\n !isNullOrUndefined(filteredResult[0].result.aggregateFields),\n 'aggregationQueryResponse.result.aggregateFields'\n );\n\n // Remap the short-form aliases that were sent to the server\n // to the client-side aliases. Users will access the results\n // using the client-side alias.\n const unmappedAggregateFields = filteredResult[0].result?.aggregateFields;\n const remappedFields = Object.keys(unmappedAggregateFields).reduce<\n ApiClientObjectMap<Value>\n >((accumulator, key) => {\n debugAssert(\n !isNullOrUndefined(aliasMap[key]),\n `'${key}' not present in aliasMap result`\n );\n accumulator[aliasMap[key]] = unmappedAggregateFields[key]!;\n return accumulator;\n }, {});\n\n return remappedFields;\n}\n\nexport function newPersistentWriteStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WriteStreamListener\n): PersistentWriteStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentWriteStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n\nexport function newPersistentWatchStream(\n datastore: Datastore,\n queue: AsyncQueue,\n listener: WatchStreamListener\n): PersistentListenStream {\n const datastoreImpl = debugCast(datastore, DatastoreImpl);\n datastoreImpl.verifyInitialized();\n return new PersistentListenStream(\n queue,\n datastoreImpl.connection,\n datastoreImpl.authCredentials,\n datastoreImpl.appCheckCredentials,\n datastoreImpl.serializer,\n listener\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OnlineState } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\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: DelayedOperation<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 debugAssert(\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 debugAssert(\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 debugAssert(\n this.watchStreamFailures === 0,\n 'watchStreamFailures must be 0'\n );\n debugAssert(\n this.onlineStateTimer === null,\n 'onlineStateTimer must be null'\n );\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 logError(message);\n this.shouldWarnClientIsOffline = false;\n } else {\n logDebug(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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { OnlineState, TargetId } from '../core/types';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreGetLastRemoteSnapshotVersion,\n localStoreGetNextMutationBatch\n} from '../local/local_store_impl';\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { TargetData } from '../local/target_data';\nimport { MutationResult } from '../model/mutation';\nimport { MutationBatch, MutationBatchResult } from '../model/mutation_batch';\nimport { debugAssert, debugCast } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\nimport {\n Datastore,\n newPersistentWatchStream,\n newPersistentWriteStream\n} from './datastore';\nimport { OnlineStateTracker } from './online_state_tracker';\nimport {\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\nimport { RemoteSyncer } from './remote_syncer';\nimport { isPermanentWriteError } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\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/** Reasons for why the RemoteStore may be offline. */\nconst enum OfflineCause {\n /** The user has explicitly disabled the network (via `disableNetwork()`). */\n UserDisabled,\n /** An IndexedDb failure occurred while persisting a stream update. */\n IndexedDbFailed,\n /** The tab is not the primary tab (only relevant with multi-tab). */\n IsSecondary,\n /** We are restarting the streams due to an Auth credential change. */\n CredentialChange,\n /** The connectivity state of the environment has changed. */\n ConnectivityChange,\n /** The RemoteStore has been shut down. */\n Shutdown\n}\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 interface RemoteStore {\n /**\n * SyncEngine to notify of watch and write events. This must be set\n * immediately after construction.\n */\n remoteSyncer: RemoteSyncer;\n}\n\nclass RemoteStoreImpl implements RemoteStore {\n remoteSyncer: RemoteSyncer = {};\n\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 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 listenTargets = new Map<TargetId, TargetData>();\n\n connectivityMonitor: ConnectivityMonitor;\n watchStream?: PersistentListenStream;\n writeStream?: PersistentWriteStream;\n watchChangeAggregator?: WatchChangeAggregator;\n\n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n offlineCauses = new Set<OfflineCause>();\n\n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n onNetworkStatusChange: Array<(enabled: boolean) => Promise<void>> = [];\n\n onlineStateTracker: OnlineStateTracker;\n\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n readonly localStore: LocalStore,\n /** The client-side proxy for interacting with the backend. */\n readonly datastore: Datastore,\n readonly asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n ) {\n this.connectivityMonitor = connectivityMonitor;\n this.connectivityMonitor.addCallback((_: NetworkStatus) => {\n asyncQueue.enqueueAndForget(async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n if (canUseNetwork(this)) {\n logDebug(\n LOG_TAG,\n 'Restarting streams for network reachability change.'\n );\n await restartNetwork(this);\n }\n });\n });\n\n this.onlineStateTracker = new OnlineStateTracker(\n asyncQueue,\n onlineStateHandler\n );\n }\n}\n\nexport function newRemoteStore(\n localStore: LocalStore,\n datastore: Datastore,\n asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n): RemoteStore {\n return new RemoteStoreImpl(\n localStore,\n datastore,\n asyncQueue,\n onlineStateHandler,\n connectivityMonitor\n );\n}\n\n/** Re-enables the network. Idempotent. */\nexport function remoteStoreEnableNetwork(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.UserDisabled);\n return enableNetworkInternal(remoteStoreImpl);\n}\n\nasync function enableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n if (canUseNetwork(remoteStoreImpl)) {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ true);\n }\n }\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\nexport async function remoteStoreDisableNetwork(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.UserDisabled);\n await disableNetworkInternal(remoteStoreImpl);\n\n // Set the OnlineState to Offline so get()s return from cache, etc.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n}\n\nasync function disableNetworkInternal(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ false);\n }\n}\n\nexport async function remoteStoreShutdown(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n logDebug(LOG_TAG, 'RemoteStore shutting down.');\n remoteStoreImpl.offlineCauses.add(OfflineCause.Shutdown);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.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 remoteStoreImpl.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 */\nexport function remoteStoreListen(\n remoteStore: RemoteStore,\n targetData: TargetData\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n\n if (remoteStoreImpl.listenTargets.has(targetData.targetId)) {\n return;\n }\n\n // Mark this as something the client is currently listening for.\n remoteStoreImpl.listenTargets.set(targetData.targetId, targetData);\n\n if (shouldStartWatchStream(remoteStoreImpl)) {\n // The listen will be sent in onWatchStreamOpen\n startWatchStream(remoteStoreImpl);\n } else if (ensureWatchStream(remoteStoreImpl).isOpen()) {\n sendWatchRequest(remoteStoreImpl, 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 */\nexport function remoteStoreUnlisten(\n remoteStore: RemoteStore,\n targetId: TargetId\n): void {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const watchStream = ensureWatchStream(remoteStoreImpl);\n\n debugAssert(\n remoteStoreImpl.listenTargets.has(targetId),\n `unlisten called on target no currently watched: ${targetId}`\n );\n\n remoteStoreImpl.listenTargets.delete(targetId);\n if (watchStream.isOpen()) {\n sendUnwatchRequest(remoteStoreImpl, targetId);\n }\n\n if (remoteStoreImpl.listenTargets.size === 0) {\n if (watchStream.isOpen()) {\n watchStream.markIdle();\n } else if (canUseNetwork(remoteStoreImpl)) {\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 remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\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 */\nfunction sendWatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetData: TargetData\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(\n targetData.targetId\n );\n\n if (\n targetData.resumeToken.approximateByteSize() > 0 ||\n targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0\n ) {\n const expectedCount = remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(\n targetData.targetId\n ).size;\n targetData = targetData.withExpectedCount(expectedCount);\n }\n\n ensureWatchStream(remoteStoreImpl).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 */\nfunction sendUnwatchRequest(\n remoteStoreImpl: RemoteStoreImpl,\n targetId: TargetId\n): void {\n remoteStoreImpl.watchChangeAggregator!.recordPendingTargetRequest(targetId);\n ensureWatchStream(remoteStoreImpl).unwatch(targetId);\n}\n\nfunction startWatchStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWatchStream(remoteStoreImpl),\n 'startWatchStream() called when shouldStartWatchStream() is false.'\n );\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget,\n 'getRemoteKeysForTarget() not set'\n );\n\n remoteStoreImpl.watchChangeAggregator = new WatchChangeAggregator({\n getRemoteKeysForTarget: targetId =>\n remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget!(targetId),\n getTargetDataForTarget: targetId =>\n remoteStoreImpl.listenTargets.get(targetId) || null,\n getDatabaseId: () => remoteStoreImpl.datastore.serializer.databaseId\n });\n ensureWatchStream(remoteStoreImpl).start();\n remoteStoreImpl.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 */\nfunction shouldStartWatchStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWatchStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.listenTargets.size > 0\n );\n}\n\nexport function canUseNetwork(remoteStore: RemoteStore): boolean {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.offlineCauses.size === 0;\n}\n\nfunction cleanUpWatchStreamState(remoteStoreImpl: RemoteStoreImpl): void {\n remoteStoreImpl.watchChangeAggregator = undefined;\n}\n\nasync function onWatchStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n remoteStoreImpl.listenTargets.forEach((targetData, targetId) => {\n sendWatchRequest(remoteStoreImpl, targetData);\n });\n}\n\nasync function onWatchStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWatchStream(remoteStoreImpl),\n 'Watch stream was stopped gracefully while still needed.'\n );\n }\n\n cleanUpWatchStreamState(remoteStoreImpl);\n\n // If we still need the watch stream, retry the connection.\n if (shouldStartWatchStream(remoteStoreImpl)) {\n remoteStoreImpl.onlineStateTracker.handleWatchStreamFailure(error!);\n\n startWatchStream(remoteStoreImpl);\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 remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\nasync function onWatchStreamChange(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchChange,\n snapshotVersion: SnapshotVersion\n): Promise<void> {\n // Mark the client as online since we got a message from the server\n remoteStoreImpl.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 try {\n await handleTargetError(remoteStoreImpl, watchChange);\n } catch (e) {\n logDebug(\n LOG_TAG,\n 'Failed to remove targets %s: %s ',\n watchChange.targetIds.join(','),\n e\n );\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n return;\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n remoteStoreImpl.watchChangeAggregator!.handleDocumentChange(watchChange);\n } else if (watchChange instanceof ExistenceFilterChange) {\n remoteStoreImpl.watchChangeAggregator!.handleExistenceFilter(watchChange);\n } else {\n debugAssert(\n watchChange instanceof WatchTargetChange,\n 'Expected watchChange to be an instance of WatchTargetChange'\n );\n remoteStoreImpl.watchChangeAggregator!.handleTargetChange(watchChange);\n }\n\n if (!snapshotVersion.isEqual(SnapshotVersion.min())) {\n try {\n const lastRemoteSnapshotVersion =\n await localStoreGetLastRemoteSnapshotVersion(\n remoteStoreImpl.localStore\n );\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 raiseWatchSnapshot(remoteStoreImpl, snapshotVersion);\n }\n } catch (e) {\n logDebug(LOG_TAG, 'Failed to raise snapshot:', e);\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */\nasync function disableNetworkUntilRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n e: FirestoreError,\n op?: () => Promise<unknown>\n): Promise<void> {\n if (isIndexedDbTransactionError(e)) {\n debugAssert(\n !remoteStoreImpl.offlineCauses.has(OfflineCause.IndexedDbFailed),\n 'Unexpected network event when IndexedDB was marked failed.'\n );\n remoteStoreImpl.offlineCauses.add(OfflineCause.IndexedDbFailed);\n\n // Disable network and raise offline snapshots\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Offline);\n\n if (!op) {\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n op = () =>\n localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore);\n }\n\n // Probe IndexedDB periodically and re-enable network\n remoteStoreImpl.asyncQueue.enqueueRetryable(async () => {\n logDebug(LOG_TAG, 'Retrying IndexedDB access');\n await op!();\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IndexedDbFailed);\n await enableNetworkInternal(remoteStoreImpl);\n });\n } else {\n throw e;\n }\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */\nfunction executeWithRecovery(\n remoteStoreImpl: RemoteStoreImpl,\n op: () => Promise<void>\n): Promise<void> {\n return op().catch(e => disableNetworkUntilRecovery(remoteStoreImpl, e, op));\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 */\nfunction raiseWatchSnapshot(\n remoteStoreImpl: RemoteStoreImpl,\n snapshotVersion: SnapshotVersion\n): Promise<void> {\n debugAssert(\n !snapshotVersion.isEqual(SnapshotVersion.min()),\n \"Can't raise event for unknown SnapshotVersion\"\n );\n const remoteEvent =\n remoteStoreImpl.watchChangeAggregator!.createRemoteEvent(snapshotVersion);\n\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n remoteEvent.targetChanges.forEach((change, targetId) => {\n if (change.resumeToken.approximateByteSize() > 0) {\n const targetData = remoteStoreImpl.listenTargets.get(targetId);\n // A watched target might have been removed already.\n if (targetData) {\n remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(change.resumeToken, 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, targetPurpose) => {\n const targetData = remoteStoreImpl.listenTargets.get(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 remoteStoreImpl.listenTargets.set(\n targetId,\n targetData.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n targetData.snapshotVersion\n )\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 sendUnwatchRequest(remoteStoreImpl, 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,\n targetData.sequenceNumber\n );\n sendWatchRequest(remoteStoreImpl, requestTargetData);\n });\n\n // Finally raise remote event\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applyRemoteEvent,\n 'applyRemoteEvent() not set'\n );\n return remoteStoreImpl.remoteSyncer.applyRemoteEvent(remoteEvent);\n}\n\n/** Handles an error on a target */\nasync function handleTargetError(\n remoteStoreImpl: RemoteStoreImpl,\n watchChange: WatchTargetChange\n): Promise<void> {\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectListen,\n 'rejectListen() not set'\n );\n debugAssert(!!watchChange.cause, 'Handling target error without a cause');\n const error = watchChange.cause!;\n for (const targetId of watchChange.targetIds) {\n // A watched target might have been removed already.\n if (remoteStoreImpl.listenTargets.has(targetId)) {\n await remoteStoreImpl.remoteSyncer.rejectListen(targetId, error);\n remoteStoreImpl.listenTargets.delete(targetId);\n remoteStoreImpl.watchChangeAggregator!.removeTarget(targetId);\n }\n }\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 */\nexport async function fillWritePipeline(\n remoteStore: RemoteStore\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n const writeStream = ensureWriteStream(remoteStoreImpl);\n\n let lastBatchIdRetrieved =\n remoteStoreImpl.writePipeline.length > 0\n ? remoteStoreImpl.writePipeline[remoteStoreImpl.writePipeline.length - 1]\n .batchId\n : BATCHID_UNKNOWN;\n\n while (canAddToWritePipeline(remoteStoreImpl)) {\n try {\n const batch = await localStoreGetNextMutationBatch(\n remoteStoreImpl.localStore,\n lastBatchIdRetrieved\n );\n\n if (batch === null) {\n if (remoteStoreImpl.writePipeline.length === 0) {\n writeStream.markIdle();\n }\n break;\n } else {\n lastBatchIdRetrieved = batch.batchId;\n addToWritePipeline(remoteStoreImpl, batch);\n }\n } catch (e) {\n await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);\n }\n }\n\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\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 */\nfunction canAddToWritePipeline(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n remoteStoreImpl.writePipeline.length < MAX_PENDING_WRITES\n );\n}\n\n// For testing\nexport function outstandingWrites(remoteStore: RemoteStore): number {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n return remoteStoreImpl.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 */\nfunction addToWritePipeline(\n remoteStoreImpl: RemoteStoreImpl,\n batch: MutationBatch\n): void {\n debugAssert(\n canAddToWritePipeline(remoteStoreImpl),\n 'addToWritePipeline called when pipeline is full'\n );\n remoteStoreImpl.writePipeline.push(batch);\n\n const writeStream = ensureWriteStream(remoteStoreImpl);\n if (writeStream.isOpen() && writeStream.handshakeComplete) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nfunction shouldStartWriteStream(remoteStoreImpl: RemoteStoreImpl): boolean {\n return (\n canUseNetwork(remoteStoreImpl) &&\n !ensureWriteStream(remoteStoreImpl).isStarted() &&\n remoteStoreImpl.writePipeline.length > 0\n );\n}\n\nfunction startWriteStream(remoteStoreImpl: RemoteStoreImpl): void {\n debugAssert(\n shouldStartWriteStream(remoteStoreImpl),\n 'startWriteStream() called when shouldStartWriteStream() is false.'\n );\n ensureWriteStream(remoteStoreImpl).start();\n}\n\nasync function onWriteStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n ensureWriteStream(remoteStoreImpl).writeHandshake();\n}\n\nasync function onWriteHandshakeComplete(\n remoteStoreImpl: RemoteStoreImpl\n): Promise<void> {\n const writeStream = ensureWriteStream(remoteStoreImpl);\n // Send the write pipeline now that the stream is established.\n for (const batch of remoteStoreImpl.writePipeline) {\n writeStream.writeMutations(batch.mutations);\n }\n}\n\nasync function onMutationResult(\n remoteStoreImpl: RemoteStoreImpl,\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 debugAssert(\n remoteStoreImpl.writePipeline.length > 0,\n 'Got result for empty write pipeline'\n );\n const batch = remoteStoreImpl.writePipeline.shift()!;\n const success = MutationBatchResult.from(batch, commitVersion, results);\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.applySuccessfulWrite,\n 'applySuccessfulWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.applySuccessfulWrite!(success)\n );\n\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n}\n\nasync function onWriteStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n debugAssert(\n !shouldStartWriteStream(remoteStoreImpl),\n 'Write stream was stopped gracefully while still needed.'\n );\n }\n\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n if (error && ensureWriteStream(remoteStoreImpl).handshakeComplete) {\n // This error affects the actual write.\n await handleWriteError(remoteStoreImpl, error!);\n }\n\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (shouldStartWriteStream(remoteStoreImpl)) {\n startWriteStream(remoteStoreImpl);\n }\n}\n\nasync function handleWriteError(\n remoteStoreImpl: RemoteStoreImpl,\n error: FirestoreError\n): 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 = remoteStoreImpl.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 ensureWriteStream(remoteStoreImpl).inhibitBackoff();\n\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.rejectFailedWrite,\n 'rejectFailedWrite() not set'\n );\n await executeWithRecovery(remoteStoreImpl, () =>\n remoteStoreImpl.remoteSyncer.rejectFailedWrite!(batch.batchId, error)\n );\n\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n // Transient error, just let the retry logic kick in.\n }\n}\n\nasync function restartNetwork(remoteStore: RemoteStore): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.offlineCauses.add(OfflineCause.ConnectivityChange);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.ConnectivityChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\nexport async function remoteStoreHandleCredentialChange(\n remoteStore: RemoteStore,\n user: User\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n remoteStoreImpl.asyncQueue.verifyOperationInProgress();\n debugAssert(\n !!remoteStoreImpl.remoteSyncer.handleCredentialChange,\n 'handleCredentialChange() not set'\n );\n\n logDebug(LOG_TAG, 'RemoteStore received new credentials');\n const usesNetwork = canUseNetwork(remoteStoreImpl);\n\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n remoteStoreImpl.offlineCauses.add(OfflineCause.CredentialChange);\n await disableNetworkInternal(remoteStoreImpl);\n if (usesNetwork) {\n // Don't set the network status to Unknown if we are offline.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n await remoteStoreImpl.remoteSyncer.handleCredentialChange(user);\n remoteStoreImpl.offlineCauses.delete(OfflineCause.CredentialChange);\n await enableNetworkInternal(remoteStoreImpl);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */\nexport async function remoteStoreApplyPrimaryState(\n remoteStore: RemoteStore,\n isPrimary: boolean\n): Promise<void> {\n const remoteStoreImpl = debugCast(remoteStore, RemoteStoreImpl);\n if (isPrimary) {\n remoteStoreImpl.offlineCauses.delete(OfflineCause.IsSecondary);\n await enableNetworkInternal(remoteStoreImpl);\n } else if (!isPrimary) {\n remoteStoreImpl.offlineCauses.add(OfflineCause.IsSecondary);\n await disableNetworkInternal(remoteStoreImpl);\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWatchStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentListenStream {\n if (!remoteStoreImpl.watchStream) {\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.watchStream = newPersistentWatchStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onOpen: onWatchStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWatchStreamClose.bind(null, remoteStoreImpl),\n onWatchChange: onWatchStreamChange.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.watchStream!.inhibitBackoff();\n if (shouldStartWatchStream(remoteStoreImpl)) {\n startWatchStream(remoteStoreImpl);\n } else {\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Unknown);\n }\n } else {\n await remoteStoreImpl.watchStream!.stop();\n cleanUpWatchStreamState(remoteStoreImpl);\n }\n });\n }\n\n return remoteStoreImpl.watchStream;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */\nfunction ensureWriteStream(\n remoteStoreImpl: RemoteStoreImpl\n): PersistentWriteStream {\n if (!remoteStoreImpl.writeStream) {\n debugAssert(\n remoteStoreImpl.writePipeline.length === 0,\n 'Should not issue writes before WriteStream is enabled'\n );\n\n // Create stream (but note that it is not started yet).\n remoteStoreImpl.writeStream = newPersistentWriteStream(\n remoteStoreImpl.datastore,\n remoteStoreImpl.asyncQueue,\n {\n onOpen: onWriteStreamOpen.bind(null, remoteStoreImpl),\n onClose: onWriteStreamClose.bind(null, remoteStoreImpl),\n onHandshakeComplete: onWriteHandshakeComplete.bind(\n null,\n remoteStoreImpl\n ),\n onMutationResult: onMutationResult.bind(null, remoteStoreImpl)\n }\n );\n\n remoteStoreImpl.onNetworkStatusChange.push(async enabled => {\n if (enabled) {\n remoteStoreImpl.writeStream!.inhibitBackoff();\n\n // This will start the write stream if necessary.\n await fillWritePipeline(remoteStoreImpl);\n } else {\n await remoteStoreImpl.writeStream!.stop();\n\n if (remoteStoreImpl.writePipeline.length > 0) {\n logDebug(\n LOG_TAG,\n `Stopping write stream with ${remoteStoreImpl.writePipeline.length} pending writes`\n );\n remoteStoreImpl.writePipeline = [];\n }\n }\n });\n }\n\n return remoteStoreImpl.writeStream;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\n\nimport { Code, FirestoreError } from './error';\nimport { logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 5 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. The health check is used to mark\n * a stream healthy if it has not received an error during its initial setup.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n HealthCheckTimeout = 'health_check_timeout',\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 TransactionRetry = 'transaction_retry',\n\n /**\n * A timer used to retry operations scheduled via retryable AsyncQueue\n * operations.\n */\n AsyncQueueRetry = 'async_queue_retry',\n\n /**\n * A timer used to periodically attempt index backfill.\n */\n IndexBackfill = 'index_backfill'\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 *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nexport class DelayedOperation<T extends unknown> implements PromiseLike<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 get promise(): Promise<T> {\n return this.deferred.promise;\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 then = this.deferred.promise.then.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 interface AsyncQueue {\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 readonly isShuttingDown: boolean;\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\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 enqueueAndForgetEvenWhileRestricted<T extends unknown>(\n op: () => Promise<T>\n ): void;\n\n /**\n * Initialize the shutdown of this queue. Once this method is called, the\n * only possible way to request running an operation is through\n * `enqueueEvenWhileRestricted()`.\n *\n * @param purgeExistingTasks Whether already enqueued tasked should be\n * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults\n * to false.\n */\n enterRestrictedMode(purgeExistingTasks?: boolean): void;\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\n /**\n * Enqueue a retryable operation.\n *\n * A retryable operation is rescheduled with backoff if it fails with a\n * IndexedDbTransactionError (the error type used by SimpleDb). All\n * retryable operations are executed in order and only run if all prior\n * operations were retried successfully.\n */\n enqueueRetryable(op: () => Promise<void>): void;\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel\n * or fast-forward the operation prior to its running.\n */\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): DelayedOperation<T>;\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}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */\nexport function wrapInUserErrorIfRecoverable(\n e: Error,\n msg: string\n): FirestoreError {\n logError(LOG_TAG, `${msg}: ${e}`);\n if (isIndexedDbTransactionError(e)) {\n return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`);\n } else {\n throw e;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKeySet } from '../model/collections';\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 { Query, queryEquals } from './query';\n\nexport const enum ChangeType {\n Added,\n Removed,\n Modified,\n Metadata\n}\n\nexport interface DocumentViewChange {\n type: ChangeType;\n doc: Document;\n}\n\nexport const enum SyncState {\n Local,\n Synced\n}\n\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nexport class DocumentChangeSet {\n private changeMap = new SortedMap<DocumentKey, DocumentViewChange>(\n DocumentKey.comparator\n );\n\n track(change: DocumentViewChange): void {\n const key = change.doc.key;\n const oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n\n // Merge the new change with the existing change.\n if (\n change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata\n ) {\n this.changeMap = this.changeMap.insert(key, change);\n } else if (\n change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.remove(key);\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n } else if (\n change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else {\n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail(\n 'unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange)\n );\n }\n }\n\n getChanges(): DocumentViewChange[] {\n const changes: DocumentViewChange[] = [];\n this.changeMap.inorderTraversal(\n (key: DocumentKey, change: DocumentViewChange) => {\n changes.push(change);\n }\n );\n return changes;\n }\n}\n\nexport class ViewSnapshot {\n constructor(\n readonly query: Query,\n readonly docs: DocumentSet,\n readonly oldDocs: DocumentSet,\n readonly docChanges: DocumentViewChange[],\n readonly mutatedKeys: DocumentKeySet,\n readonly fromCache: boolean,\n readonly syncStateChanged: boolean,\n readonly excludesMetadataChanges: boolean,\n readonly hasCachedResults: 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 hasCachedResults: 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 hasCachedResults\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.hasCachedResults !== other.hasCachedResults ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.mutatedKeys.isEqual(other.mutatedKeys) ||\n !queryEquals(this.query, 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert, debugCast } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { EventHandler } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { canonifyQuery, Query, queryEquals, stringifyQuery } from './query';\nimport { OnlineState } from './types';\nimport { ChangeType, DocumentViewChange, 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 | undefined = undefined;\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<FirestoreError>;\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 *\n * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be\n * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This\n * allows users to tree-shake the Watch logic.\n */\nexport interface EventManager {\n onListen?: (query: Query) => Promise<ViewSnapshot>;\n onUnlisten?: (query: Query) => Promise<void>;\n}\n\nexport function newEventManager(): EventManager {\n return new EventManagerImpl();\n}\n\nexport class EventManagerImpl implements EventManager {\n queries = new ObjectMap<Query, QueryListenersInfo>(\n q => canonifyQuery(q),\n queryEquals\n );\n\n onlineState = OnlineState.Unknown;\n\n snapshotsInSyncListeners: Set<Observer<void>> = new Set();\n\n /** Callback invoked when a Query is first listen to. */\n onListen?: (query: Query) => Promise<ViewSnapshot>;\n /** Callback invoked once all listeners to a Query are removed. */\n onUnlisten?: (query: Query) => Promise<void>;\n}\n\nexport async function eventManagerListen(\n eventManager: EventManager,\n listener: QueryListener\n): Promise<void> {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n debugAssert(!!eventManagerImpl.onListen, 'onListen not set');\n const query = listener.query;\n let firstListen = false;\n\n let queryInfo = eventManagerImpl.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n }\n\n if (firstListen) {\n try {\n queryInfo.viewSnap = await eventManagerImpl.onListen(query);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Initialization of query '${stringifyQuery(listener.query)}' failed`\n );\n listener.onError(firestoreError);\n return;\n }\n }\n\n eventManagerImpl.queries.set(query, queryInfo);\n queryInfo.listeners.push(listener);\n\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n const raisedEvent = listener.applyOnlineStateChange(\n eventManagerImpl.onlineState\n );\n debugAssert(\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 raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n }\n}\n\nexport async function eventManagerUnlisten(\n eventManager: EventManager,\n listener: QueryListener\n): Promise<void> {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n debugAssert(!!eventManagerImpl.onUnlisten, 'onUnlisten not set');\n const query = listener.query;\n let lastListen = false;\n\n const queryInfo = eventManagerImpl.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 eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten(query);\n }\n}\n\nexport function eventManagerOnWatchChange(\n eventManager: EventManager,\n viewSnaps: ViewSnapshot[]\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n let raisedEvent = false;\n for (const viewSnap of viewSnaps) {\n const query = viewSnap.query;\n const queryInfo = eventManagerImpl.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 raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function eventManagerOnWatchError(\n eventManager: EventManager,\n query: Query,\n error: FirestoreError\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n const queryInfo = eventManagerImpl.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 eventManagerImpl.queries.delete(query);\n}\n\nexport function eventManagerOnOnlineStateChange(\n eventManager: EventManager,\n onlineState: OnlineState\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.onlineState = onlineState;\n let raisedEvent = false;\n eventManagerImpl.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 raiseSnapshotsInSyncEvent(eventManagerImpl);\n }\n}\n\nexport function addSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer<void>\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n\n eventManagerImpl.snapshotsInSyncListeners.add(observer);\n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n observer.next();\n}\n\nexport function removeSnapshotsInSyncListener(\n eventManager: EventManager,\n observer: Observer<void>\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n eventManagerImpl.snapshotsInSyncListeners.delete(observer);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction raiseSnapshotsInSyncEvent(eventManagerImpl: EventManagerImpl): void {\n eventManagerImpl.snapshotsInSyncListeners.forEach(observer => {\n observer.next();\n });\n}\n\nexport interface ListenOptions {\n /** Raise events even when only the metadata changes */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Wait for a sync with the server when online, but still raise events while\n * offline.\n */\n readonly waitForSyncWhenOnline?: boolean;\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nexport class QueryListener {\n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n private raisedInitialEvent = false;\n\n private options: ListenOptions;\n\n private snap: ViewSnapshot | null = null;\n\n private onlineState = OnlineState.Unknown;\n\n constructor(\n readonly query: Query,\n private queryObserver: Observer<ViewSnapshot>,\n options?: ListenOptions\n ) {\n this.options = options || {};\n }\n\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */\n onViewSnapshot(snap: ViewSnapshot): boolean {\n debugAssert(\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 snap.hasCachedResults\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: FirestoreError): 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 debugAssert(\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 debugAssert(\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, have cached results before,\n // or we are offline.\n return (\n !snap.docs.isEmpty() ||\n snap.hasCachedResults ||\n onlineState === OnlineState.Offline\n );\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 debugAssert(\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 snap.hasCachedResults\n );\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BundleElement,\n BundleMetadata\n} from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */\nexport class SizedBundleElement {\n constructor(\n public readonly payload: BundleElement,\n // How many bytes this element takes to store in the bundle.\n public readonly byteLength: number\n ) {}\n\n isBundleMetadata(): boolean {\n return 'metadata' in this.payload;\n }\n}\n\nexport type BundleSource =\n | ReadableStream<Uint8Array>\n | ArrayBuffer\n | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n serializer: JsonProtoSerializer;\n\n close(): Promise<void>;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): Promise<BundleMetadata>;\n\n /**\n * Returns the next BundleElement (together with its byte size in the bundle)\n * that has not been read from underlying ReadableStream. Returns null if we\n * have reached the end of the stream.\n */\n nextElement(): Promise<SizedBundleElement | null>;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTaskProgress } from '@firebase/firestore-types';\n\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreApplyBundledDocuments,\n localStoreSaveNamedQuery\n} from '../local/local_store_impl';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api';\nimport {\n fromDocument,\n fromName,\n fromVersion,\n JsonProtoSerializer\n} from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { SizedBundleElement } from '../util/bundle_reader';\n\nimport {\n BundleConverter,\n BundledDocument,\n BundledDocuments,\n BundleLoadResult\n} from './bundle';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */\nexport class BundleConverterImpl implements BundleConverter {\n constructor(private readonly serializer: JsonProtoSerializer) {}\n\n toDocumentKey(name: string): DocumentKey {\n return fromName(this.serializer, name);\n }\n\n /**\n * Converts a BundleDocument to a MutableDocument.\n */\n toMutableDocument(bundledDoc: BundledDocument): MutableDocument {\n if (bundledDoc.metadata.exists) {\n debugAssert(\n !!bundledDoc.document,\n 'Document is undefined when metadata.exist is true.'\n );\n return fromDocument(this.serializer, bundledDoc.document!, false);\n } else {\n return MutableDocument.newNoDocument(\n this.toDocumentKey(bundledDoc.metadata.name!),\n this.toSnapshotVersion(bundledDoc.metadata.readTime!)\n );\n }\n }\n\n toSnapshotVersion(time: ApiTimestamp): SnapshotVersion {\n return fromVersion(time);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */\nexport class BundleLoader {\n /** The current progress of loading */\n private progress: LoadBundleTaskProgress;\n /** Batched queries to be saved into storage */\n private queries: ProtoNamedQuery[] = [];\n /** Batched documents to be saved into storage */\n private documents: BundledDocuments = [];\n /** The collection groups affected by this bundle. */\n private collectionGroups = new Set<string>();\n\n constructor(\n private bundleMetadata: ProtoBundleMetadata,\n private localStore: LocalStore,\n private serializer: JsonProtoSerializer\n ) {\n this.progress = bundleInitialProgress(bundleMetadata);\n }\n\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */\n addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null {\n debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');\n\n this.progress.bytesLoaded += element.byteLength;\n\n let documentsLoaded = this.progress.documentsLoaded;\n\n if (element.payload.namedQuery) {\n this.queries.push(element.payload.namedQuery);\n } else if (element.payload.documentMetadata) {\n this.documents.push({ metadata: element.payload.documentMetadata });\n if (!element.payload.documentMetadata.exists) {\n ++documentsLoaded;\n }\n const path = ResourcePath.fromString(\n element.payload.documentMetadata.name!\n );\n debugAssert(\n path.length >= 2,\n 'The document name does not point to a document.'\n );\n this.collectionGroups.add(path.get(path.length - 2));\n } else if (element.payload.document) {\n debugAssert(\n this.documents.length > 0 &&\n this.documents[this.documents.length - 1].metadata.name ===\n element.payload.document.name,\n 'The document being added does not match the stored metadata.'\n );\n this.documents[this.documents.length - 1].document =\n element.payload.document;\n ++documentsLoaded;\n }\n\n if (documentsLoaded !== this.progress.documentsLoaded) {\n this.progress.documentsLoaded = documentsLoaded;\n return { ...this.progress };\n }\n\n return null;\n }\n\n private getQueryDocumentMapping(\n documents: BundledDocuments\n ): Map<string, DocumentKeySet> {\n const queryDocumentMap = new Map<string, DocumentKeySet>();\n const bundleConverter = new BundleConverterImpl(this.serializer);\n for (const bundleDoc of documents) {\n if (bundleDoc.metadata.queries) {\n const documentKey = bundleConverter.toDocumentKey(\n bundleDoc.metadata.name!\n );\n for (const queryName of bundleDoc.metadata.queries) {\n const documentKeys = (\n queryDocumentMap.get(queryName) || documentKeySet()\n ).add(documentKey);\n queryDocumentMap.set(queryName, documentKeys);\n }\n }\n }\n\n return queryDocumentMap;\n }\n\n /**\n * Update the progress to 'Success' and return the updated progress.\n */\n async complete(): Promise<BundleLoadResult> {\n debugAssert(\n this.documents[this.documents.length - 1]?.metadata.exists !== true ||\n !!this.documents[this.documents.length - 1].document,\n 'Bundled documents end with a document metadata element instead of a document.'\n );\n debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n const changedDocs = await localStoreApplyBundledDocuments(\n this.localStore,\n new BundleConverterImpl(this.serializer),\n this.documents,\n this.bundleMetadata.id!\n );\n\n const queryDocumentMap = this.getQueryDocumentMapping(this.documents);\n\n for (const q of this.queries) {\n await localStoreSaveNamedQuery(\n this.localStore,\n q,\n queryDocumentMap.get(q.name!)\n );\n }\n\n this.progress.taskState = 'Success';\n return {\n progress: this.progress,\n changedCollectionGroups: this.collectionGroups,\n changedDocs\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */\nexport function bundleInitialProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Running',\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\nexport function bundleSuccessProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Success',\n documentsLoaded: metadata.totalDocuments!,\n bytesLoaded: metadata.totalBytes!,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } 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 private hasCachedResults: boolean = false;\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 /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\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 * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\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.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\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.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.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 // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\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 debugAssert(\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 limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n limboResolutionEnabled: boolean,\n targetChange?: TargetChange,\n targetIsPendingReset?: boolean\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\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.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n\n targetIsPendingReset = targetIsPendingReset ?? false;\n const limboChanges =\n limboResolutionEnabled && !targetIsPendingReset\n ? this.updateLimboDocuments()\n : [];\n\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n const synced =\n this.limboDocuments.size === 0 && this.current && !targetIsPendingReset;\n\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 targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : 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 /* limboResolutionEnabled= */ 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 debugAssert(\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 * @returns 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, /* limboResolutionEnabled= */ 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 this.hasCachedResults\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTask } from '../api/bundle';\nimport { User } from '../auth/user';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport {\n localStoreAcknowledgeBatch,\n localStoreAllocateTarget,\n localStoreApplyRemoteEventToLocalCache,\n localStoreExecuteQuery,\n localStoreGetActiveClients,\n localStoreGetCachedTarget,\n localStoreGetHighestUnacknowledgedBatchId,\n localStoreGetNewDocumentChanges,\n localStoreHandleUserChange,\n localStoreHasNewerBundle,\n localStoreLookupMutationDocuments,\n localStoreNotifyLocalViewChanges,\n localStoreRejectBatch,\n localStoreReleaseTarget,\n localStoreRemoveCachedMutationBatchMetadata,\n localStoreSaveBundle,\n localStoreWriteLocally\n} from '../local/local_store_impl';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { ReferenceSet } from '../local/reference_set';\nimport { ClientId, SharedClientState } from '../local/shared_client_state';\nimport { QueryTargetState } from '../local/shared_client_state_syncer';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatchResult } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport {\n canUseNetwork,\n fillWritePipeline,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreListen,\n remoteStoreUnlisten\n} from '../remote/remote_store';\nimport { debugAssert, debugCast, fail, hardAssert } from '../util/assert';\nimport { wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } 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';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n bundleInitialProgress,\n BundleLoader,\n bundleSuccessProgress\n} from './bundle_impl';\nimport {\n EventManager,\n eventManagerOnOnlineStateChange,\n eventManagerOnWatchChange,\n eventManagerOnWatchError\n} from './event_manager';\nimport { ListenSequence } from './listen_sequence';\nimport {\n canonifyQuery,\n LimitType,\n newQuery,\n newQueryForPath,\n Query,\n queryEquals,\n queryCollectionGroup,\n queryToTarget,\n stringifyQuery\n} from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { SyncEngine } from './sync_engine';\nimport { Target } from './target';\nimport { TargetIdGenerator } from './target_id_generator';\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} from './view';\nimport { ViewSnapshot } from './view_snapshot';\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 * A function that updates a QueryView with a set of document changes (and a\n * remote event if applicable).\n */\ntype ApplyDocChangesHandler = (\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n) => Promise<ViewSnapshot | undefined>;\n\n/**\n * Callbacks implemented by EventManager to handle notifications from\n * SyncEngine.\n */\ninterface SyncEngineListener {\n /** Handles new view snapshots. */\n onWatchChange?(snapshots: ViewSnapshot[]): void;\n\n /** Handles the failure of a query. */\n onWatchError?(query: Query, error: FirestoreError): void;\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass SyncEngineImpl implements SyncEngine {\n syncEngineListener: SyncEngineListener = {};\n\n /**\n * A callback that updates the QueryView based on the provided change.\n *\n * PORTING NOTE: On other platforms, this logic lives in\n * `emitNewSnapshotsAndNotifyLocalStore()`, but on Web it is extracted to\n * ensure that all view logic only exists in bundles that include views.\n */\n applyDocChanges?: ApplyDocChangesHandler;\n\n queryViewsByQuery = new ObjectMap<Query, QueryView>(\n q => canonifyQuery(q),\n queryEquals\n );\n queriesByTarget = new Map<TargetId, Query[]>();\n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n enqueuedLimboResolutions = new Set<string>();\n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n activeLimboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n activeLimboResolutionsByTarget = new Map<TargetId, LimboResolution>();\n limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n mutationUserCallbacks = {} as {\n [uidKey: string]: SortedMap<BatchId, Deferred<void>>;\n };\n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n pendingWritesCallbacks = new Map<BatchId, Array<Deferred<void>>>();\n limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\n\n onlineState = OnlineState.Unknown;\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 _isPrimaryClient: undefined | boolean = undefined;\n\n constructor(\n readonly localStore: LocalStore,\n readonly remoteStore: RemoteStore,\n readonly eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n readonly sharedClientState: SharedClientState,\n public currentUser: User,\n readonly maxConcurrentLimboResolutions: number\n ) {}\n\n get isPrimaryClient(): boolean {\n return this._isPrimaryClient === true;\n }\n}\n\nexport function newSyncEngine(\n localStore: LocalStore,\n remoteStore: RemoteStore,\n eventManager: EventManager,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n sharedClientState: SharedClientState,\n currentUser: User,\n maxConcurrentLimboResolutions: number,\n isPrimary: boolean\n): SyncEngine {\n const syncEngine = new SyncEngineImpl(\n localStore,\n remoteStore,\n eventManager,\n sharedClientState,\n currentUser,\n maxConcurrentLimboResolutions\n );\n if (isPrimary) {\n syncEngine._isPrimaryClient = true;\n }\n return syncEngine;\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nexport async function syncEngineListen(\n syncEngine: SyncEngine,\n query: Query\n): Promise<ViewSnapshot> {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n\n let targetId;\n let viewSnapshot;\n\n const queryView = syncEngineImpl.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 syncEngineImpl.sharedClientState.addLocalQueryTarget(targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n } else {\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(query)\n );\n\n const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(\n targetData.targetId\n );\n targetId = targetData.targetId;\n viewSnapshot = await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n query,\n targetId,\n status === 'current',\n targetData.resumeToken\n );\n\n if (syncEngineImpl.isPrimaryClient) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n }\n\n return viewSnapshot;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */\nasync function initializeViewAndComputeSnapshot(\n syncEngineImpl: SyncEngineImpl,\n query: Query,\n targetId: TargetId,\n current: boolean,\n resumeToken: ByteString\n): Promise<ViewSnapshot> {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n syncEngineImpl.applyDocChanges = (queryView, changes, remoteEvent) =>\n applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent);\n\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const synthesizedTargetChange =\n TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current && syncEngineImpl.onlineState !== OnlineState.Offline,\n resumeToken\n );\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient,\n synthesizedTargetChange\n );\n updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges);\n\n debugAssert(\n !!viewChange.snapshot,\n 'applyChanges for new view should always return a snapshot'\n );\n\n const data = new QueryView(query, targetId, view);\n\n syncEngineImpl.queryViewsByQuery.set(query, data);\n if (syncEngineImpl.queriesByTarget.has(targetId)) {\n syncEngineImpl.queriesByTarget.get(targetId)!.push(query);\n } else {\n syncEngineImpl.queriesByTarget.set(targetId, [query]);\n }\n\n return viewChange.snapshot;\n}\n\n/** Stops listening to the query. */\nexport async function syncEngineUnlisten(\n syncEngine: SyncEngine,\n query: Query\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryView = syncEngineImpl.queryViewsByQuery.get(query)!;\n debugAssert(\n !!queryView,\n 'Trying to unlisten on query not found:' + stringifyQuery(query)\n );\n\n // Only clean up the query view and target if this is the only query mapped\n // to the target.\n const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId)!;\n if (queries.length > 1) {\n syncEngineImpl.queriesByTarget.set(\n queryView.targetId,\n queries.filter(q => !queryEquals(q, query))\n );\n syncEngineImpl.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 (syncEngineImpl.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n const targetRemainsActive =\n syncEngineImpl.sharedClientState.isActiveQueryTarget(queryView.targetId);\n\n if (!targetRemainsActive) {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n queryView.targetId,\n /*keepPersistedTargetData=*/ false\n )\n .then(() => {\n syncEngineImpl.sharedClientState.clearQueryState(queryView.targetId);\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n } else {\n removeAndCleanupTarget(syncEngineImpl, queryView.targetId);\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\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 */\nexport async function syncEngineWrite(\n syncEngine: SyncEngine,\n batch: Mutation[],\n userCallback: Deferred<void>\n): Promise<void> {\n const syncEngineImpl = syncEngineEnsureWriteCallbacks(syncEngine);\n\n try {\n const result = await localStoreWriteLocally(\n syncEngineImpl.localStore,\n batch\n );\n syncEngineImpl.sharedClientState.addPendingMutation(result.batchId);\n addMutationCallback(syncEngineImpl, result.batchId, userCallback);\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.changes\n );\n await fillWritePipeline(syncEngineImpl.remoteStore);\n } catch (e) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const error = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to persist write`\n );\n userCallback.reject(error);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */\nexport async function syncEngineApplyRemoteEvent(\n syncEngine: SyncEngine,\n remoteEvent: RemoteEvent\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreApplyRemoteEventToLocalCache(\n syncEngineImpl.localStore,\n remoteEvent\n );\n // Update `receivedDocument` as appropriate for any limbo targets.\n remoteEvent.targetChanges.forEach((targetChange, targetId) => {\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(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 hardAssert(\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 hardAssert(\n limboResolution.receivedDocument,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\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 syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n remoteEvent\n );\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\nexport function syncEngineApplyOnlineStateChange(\n syncEngine: SyncEngine,\n onlineState: OnlineState,\n source: OnlineStateSource\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\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 (syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.RemoteStore) ||\n (!syncEngineImpl.isPrimaryClient &&\n source === OnlineStateSource.SharedClientState)\n ) {\n const newViewSnapshots = [] as ViewSnapshot[];\n syncEngineImpl.queryViewsByQuery.forEach((query, queryView) => {\n const viewChange = queryView.view.applyOnlineStateChange(onlineState);\n debugAssert(\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\n eventManagerOnOnlineStateChange(syncEngineImpl.eventManager, onlineState);\n\n if (newViewSnapshots.length) {\n debugAssert(\n !!syncEngineImpl.syncEngineListener.onWatchChange,\n 'Active views but EventManager callbacks are not assigned'\n );\n syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots);\n }\n\n syncEngineImpl.onlineState = onlineState;\n if (syncEngineImpl.isPrimaryClient) {\n syncEngineImpl.sharedClientState.setOnlineState(onlineState);\n }\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */\nexport async function syncEngineRejectListen(\n syncEngine: SyncEngine,\n targetId: TargetId,\n err: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // PORTING NOTE: Multi-tab only.\n syncEngineImpl.sharedClientState.updateQueryState(targetId, 'rejected', err);\n\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n const limboKey = limboResolution && limboResolution.key;\n if (limboKey) {\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, MutableDocument>(\n DocumentKey.comparator\n );\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n documentUpdates = documentUpdates.insert(\n limboKey,\n MutableDocument.newNoDocument(limboKey, SnapshotVersion.min())\n );\n const resolvedLimboDocuments = documentKeySet().add(limboKey);\n const event = new RemoteEvent(\n SnapshotVersion.min(),\n /* targetChanges= */ new Map<TargetId, TargetChange>(),\n /* targetMismatches= */ new SortedMap<TargetId, TargetPurpose>(\n primitiveComparator\n ),\n documentUpdates,\n resolvedLimboDocuments\n );\n\n await syncEngineApplyRemoteEvent(syncEngineImpl, event);\n\n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(limboKey);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(targetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n } else {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => removeAndCleanupTarget(syncEngineImpl, targetId, err))\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nexport async function syncEngineApplySuccessfulWrite(\n syncEngine: SyncEngine,\n mutationBatchResult: MutationBatchResult\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const batchId = mutationBatchResult.batch.batchId;\n\n try {\n const changes = await localStoreAcknowledgeBatch(\n syncEngineImpl.localStore,\n mutationBatchResult\n );\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 processUserCallback(syncEngineImpl, batchId, /*error=*/ null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'acknowledged'\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\nexport async function syncEngineRejectFailedWrite(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n try {\n const changes = await localStoreRejectBatch(\n syncEngineImpl.localStore,\n batchId\n );\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 processUserCallback(syncEngineImpl, batchId, error);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n\n syncEngineImpl.sharedClientState.updateMutationState(\n batchId,\n 'rejected',\n error\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error as FirestoreError);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */\nexport async function syncEngineRegisterPendingWritesCallback(\n syncEngine: SyncEngine,\n callback: Deferred<void>\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (!canUseNetwork(syncEngineImpl.remoteStore)) {\n logDebug(\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 try {\n const highestBatchId = await localStoreGetHighestUnacknowledgedBatchId(\n syncEngineImpl.localStore\n );\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 =\n syncEngineImpl.pendingWritesCallbacks.get(highestBatchId) || [];\n callbacks.push(callback);\n syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n 'Initialization of waitForPendingWrites() operation failed'\n );\n callback.reject(firestoreError);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */\nfunction triggerPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId\n): void {\n (syncEngineImpl.pendingWritesCallbacks.get(batchId) || []).forEach(\n callback => {\n callback.resolve();\n }\n );\n\n syncEngineImpl.pendingWritesCallbacks.delete(batchId);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */\nfunction rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl: SyncEngineImpl,\n errorMessage: string\n): void {\n syncEngineImpl.pendingWritesCallbacks.forEach(callbacks => {\n callbacks.forEach(callback => {\n callback.reject(new FirestoreError(Code.CANCELLED, errorMessage));\n });\n });\n\n syncEngineImpl.pendingWritesCallbacks.clear();\n}\n\nfunction addMutationCallback(\n syncEngineImpl: SyncEngineImpl,\n batchId: BatchId,\n callback: Deferred<void>\n): void {\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap<BatchId, Deferred<void>>(primitiveComparator);\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n}\n\n/**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\nfunction processUserCallback(\n syncEngine: SyncEngine,\n batchId: BatchId,\n error: FirestoreError | null\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.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 debugAssert(\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 syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] =\n newCallbacks;\n }\n}\n\nfunction removeAndCleanupTarget(\n syncEngineImpl: SyncEngineImpl,\n targetId: number,\n error: FirestoreError | null = null\n): void {\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(targetId);\n\n debugAssert(\n syncEngineImpl.queriesByTarget.has(targetId) &&\n syncEngineImpl.queriesByTarget.get(targetId)!.length !== 0,\n `There are no queries mapped to target id ${targetId}`\n );\n\n for (const query of syncEngineImpl.queriesByTarget.get(targetId)!) {\n syncEngineImpl.queryViewsByQuery.delete(query);\n if (error) {\n syncEngineImpl.syncEngineListener.onWatchError!(query, error);\n }\n }\n\n syncEngineImpl.queriesByTarget.delete(targetId);\n\n if (syncEngineImpl.isPrimaryClient) {\n const limboKeys =\n syncEngineImpl.limboDocumentRefs.removeReferencesForId(targetId);\n limboKeys.forEach(limboKey => {\n const isReferenced =\n syncEngineImpl.limboDocumentRefs.containsKey(limboKey);\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboKey);\n }\n });\n }\n}\n\nfunction removeLimboTarget(\n syncEngineImpl: SyncEngineImpl,\n key: DocumentKey\n): void {\n syncEngineImpl.enqueuedLimboResolutions.delete(key.path.canonicalString());\n\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 = syncEngineImpl.activeLimboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n\n remoteStoreUnlisten(syncEngineImpl.remoteStore, limboTargetId);\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.remove(key);\n syncEngineImpl.activeLimboResolutionsByTarget.delete(limboTargetId);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n}\n\nfunction updateTrackedLimbos(\n syncEngineImpl: SyncEngineImpl,\n targetId: TargetId,\n limboChanges: LimboDocumentChange[]\n): void {\n for (const limboChange of limboChanges) {\n if (limboChange instanceof AddedLimboDocument) {\n syncEngineImpl.limboDocumentRefs.addReference(limboChange.key, targetId);\n trackLimboChange(syncEngineImpl, limboChange);\n } else if (limboChange instanceof RemovedLimboDocument) {\n logDebug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n syncEngineImpl.limboDocumentRefs.removeReference(\n limboChange.key,\n targetId\n );\n const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(\n limboChange.key\n );\n if (!isReferenced) {\n // We removed the last reference for this key\n removeLimboTarget(syncEngineImpl, limboChange.key);\n }\n } else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n}\n\nfunction trackLimboChange(\n syncEngineImpl: SyncEngineImpl,\n limboChange: AddedLimboDocument\n): void {\n const key = limboChange.key;\n const keyString = key.path.canonicalString();\n if (\n !syncEngineImpl.activeLimboTargetsByKey.get(key) &&\n !syncEngineImpl.enqueuedLimboResolutions.has(keyString)\n ) {\n logDebug(LOG_TAG, 'New document in limbo: ' + key);\n syncEngineImpl.enqueuedLimboResolutions.add(keyString);\n pumpEnqueuedLimboResolutions(syncEngineImpl);\n }\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */\nfunction pumpEnqueuedLimboResolutions(syncEngineImpl: SyncEngineImpl): void {\n while (\n syncEngineImpl.enqueuedLimboResolutions.size > 0 &&\n syncEngineImpl.activeLimboTargetsByKey.size <\n syncEngineImpl.maxConcurrentLimboResolutions\n ) {\n const keyString = syncEngineImpl.enqueuedLimboResolutions\n .values()\n .next().value;\n syncEngineImpl.enqueuedLimboResolutions.delete(keyString);\n const key = new DocumentKey(ResourcePath.fromString(keyString));\n const limboTargetId = syncEngineImpl.limboTargetIdGenerator.next();\n syncEngineImpl.activeLimboResolutionsByTarget.set(\n limboTargetId,\n new LimboResolution(key)\n );\n syncEngineImpl.activeLimboTargetsByKey =\n syncEngineImpl.activeLimboTargetsByKey.insert(key, limboTargetId);\n remoteStoreListen(\n syncEngineImpl.remoteStore,\n new TargetData(\n queryToTarget(newQueryForPath(key.path)),\n limboTargetId,\n TargetPurpose.LimboResolution,\n ListenSequence.INVALID\n )\n );\n }\n}\n\n// Visible for testing\nexport function syncEngineGetActiveLimboDocumentResolutions(\n syncEngine: SyncEngine\n): SortedMap<DocumentKey, TargetId> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.activeLimboTargetsByKey;\n}\n\n// Visible for testing\nexport function syncEngineGetEnqueuedLimboDocumentResolutions(\n syncEngine: SyncEngine\n): Set<string> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.enqueuedLimboResolutions;\n}\n\nexport async function syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine: SyncEngine,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const newSnaps: ViewSnapshot[] = [];\n const docChangesInAllViews: LocalViewChanges[] = [];\n const queriesProcessed: Array<Promise<void>> = [];\n\n if (syncEngineImpl.queryViewsByQuery.isEmpty()) {\n // Return early since `onWatchChange()` might not have been assigned yet.\n return;\n }\n\n syncEngineImpl.queryViewsByQuery.forEach((_, queryView) => {\n debugAssert(\n !!syncEngineImpl.applyDocChanges,\n 'ApplyDocChangesHandler not set'\n );\n queriesProcessed.push(\n syncEngineImpl\n .applyDocChanges(queryView, changes, remoteEvent)\n .then(viewSnapshot => {\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n if (viewSnapshot || remoteEvent) {\n if (syncEngineImpl.isPrimaryClient) {\n syncEngineImpl.sharedClientState.updateQueryState(\n queryView.targetId,\n viewSnapshot?.fromCache ? 'not-current' : 'current'\n );\n }\n }\n\n // Update views if there are actual changes.\n if (!!viewSnapshot) {\n newSnaps.push(viewSnapshot);\n const docChanges = LocalViewChanges.fromSnapshot(\n queryView.targetId,\n viewSnapshot\n );\n docChangesInAllViews.push(docChanges);\n }\n })\n );\n });\n\n await Promise.all(queriesProcessed);\n syncEngineImpl.syncEngineListener.onWatchChange!(newSnaps);\n await localStoreNotifyLocalViewChanges(\n syncEngineImpl.localStore,\n docChangesInAllViews\n );\n}\n\nasync function applyDocChanges(\n syncEngineImpl: SyncEngineImpl,\n queryView: QueryView,\n changes: DocumentMap,\n remoteEvent?: RemoteEvent\n): Promise<ViewSnapshot | undefined> {\n let viewDocChanges = queryView.view.computeDocChanges(changes);\n if (viewDocChanges.needsRefill) {\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 viewDocChanges = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ false\n ).then(({ documents }) => {\n return queryView.view.computeDocChanges(documents, viewDocChanges);\n });\n }\n\n const targetChange =\n remoteEvent && remoteEvent.targetChanges.get(queryView.targetId);\n const targetIsPendingReset =\n remoteEvent && remoteEvent.targetMismatches.get(queryView.targetId) != null;\n const viewChange = queryView.view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient,\n targetChange,\n targetIsPendingReset\n );\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewChange.limboChanges\n );\n return viewChange.snapshot;\n}\n\nexport async function syncEngineHandleCredentialChange(\n syncEngine: SyncEngine,\n user: User\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const userChanged = !syncEngineImpl.currentUser.isEqual(user);\n\n if (userChanged) {\n logDebug(LOG_TAG, 'User change. New user:', user.toKey());\n\n const result = await localStoreHandleUserChange(\n syncEngineImpl.localStore,\n user\n );\n syncEngineImpl.currentUser = user;\n\n // Fails tasks waiting for pending writes requested by previous user.\n rejectOutstandingPendingWritesCallbacks(\n syncEngineImpl,\n \"'waitForPendingWrites' promise is rejected due to a user change.\"\n );\n // TODO(b/114226417): Consider calling this only in the primary tab.\n syncEngineImpl.sharedClientState.handleUserChange(\n user,\n result.removedBatchIds,\n result.addedBatchIds\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n result.affectedDocuments\n );\n }\n}\n\nexport function syncEngineGetRemoteKeysForTarget(\n syncEngine: SyncEngine,\n targetId: TargetId\n): DocumentKeySet {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const limboResolution =\n syncEngineImpl.activeLimboResolutionsByTarget.get(targetId);\n if (limboResolution && limboResolution.receivedDocument) {\n return documentKeySet().add(limboResolution.key);\n } else {\n let keySet = documentKeySet();\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n if (!queries) {\n return keySet;\n }\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n keySet = keySet.unionWith(queryView.view.syncedDocuments);\n }\n return keySet;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */\nasync function synchronizeViewAndComputeSnapshot(\n syncEngine: SyncEngine,\n queryView: QueryView\n): Promise<ViewChange> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const queryResult = await localStoreExecuteQuery(\n syncEngineImpl.localStore,\n queryView.query,\n /* usePreviousResults= */ true\n );\n const viewSnapshot =\n queryView.view.synchronizeWithPersistedState(queryResult);\n if (syncEngineImpl.isPrimaryClient) {\n updateTrackedLimbos(\n syncEngineImpl,\n queryView.targetId,\n viewSnapshot.limboChanges\n );\n }\n return viewSnapshot;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineSynchronizeWithChangedDocuments(\n syncEngine: SyncEngine,\n collectionGroup: string\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n return localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n collectionGroup\n ).then(changes =>\n syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes)\n );\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyBatchState(\n syncEngine: SyncEngine,\n batchId: BatchId,\n batchState: MutationBatchState,\n error?: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const documents = await localStoreLookupMutationDocuments(\n syncEngineImpl.localStore,\n batchId\n );\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 logDebug(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 fillWritePipeline(syncEngineImpl.remoteStore);\n } else if (batchState === 'acknowledged' || batchState === 'rejected') {\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n processUserCallback(syncEngineImpl, batchId, error ? error : null);\n triggerPendingWritesCallbacks(syncEngineImpl, batchId);\n localStoreRemoveCachedMutationBatchMetadata(\n syncEngineImpl.localStore,\n batchId\n );\n } else {\n fail(`Unknown batchState: ${batchState}`);\n }\n\n await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, documents);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyPrimaryState(\n syncEngine: SyncEngine,\n isPrimary: boolean\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n ensureWatchCallbacks(syncEngineImpl);\n syncEngineEnsureWriteCallbacks(syncEngineImpl);\n if (isPrimary === true && syncEngineImpl._isPrimaryClient !== true) {\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 =\n syncEngineImpl.sharedClientState.getAllActiveQueryTargets();\n const activeQueries = await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets.toArray(),\n /*transitionToPrimary=*/ true\n );\n syncEngineImpl._isPrimaryClient = true;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, true);\n for (const targetData of activeQueries) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\n }\n } else if (isPrimary === false && syncEngineImpl._isPrimaryClient !== false) {\n const activeTargets: TargetId[] = [];\n\n let p = Promise.resolve();\n syncEngineImpl.queriesByTarget.forEach((_, targetId) => {\n if (syncEngineImpl.sharedClientState.isLocalQueryTarget(targetId)) {\n activeTargets.push(targetId);\n } else {\n p = p.then(() => {\n removeAndCleanupTarget(syncEngineImpl, targetId);\n return localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n });\n }\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n await p;\n\n await synchronizeQueryViewsAndRaiseSnapshots(\n syncEngineImpl,\n activeTargets,\n /*transitionToPrimary=*/ false\n );\n resetLimboDocuments(syncEngineImpl);\n syncEngineImpl._isPrimaryClient = false;\n await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, false);\n }\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction resetLimboDocuments(syncEngine: SyncEngine): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.activeLimboResolutionsByTarget.forEach((_, targetId) => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n });\n syncEngineImpl.limboDocumentRefs.removeAllReferences();\n syncEngineImpl.activeLimboResolutionsByTarget = new Map<\n TargetId,\n LimboResolution\n >();\n syncEngineImpl.activeLimboTargetsByKey = 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 * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n// PORTING NOTE: Multi-Tab only.\nasync function synchronizeQueryViewsAndRaiseSnapshots(\n syncEngine: SyncEngine,\n targets: TargetId[],\n transitionToPrimary: boolean\n): Promise<TargetData[]> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const activeQueries: TargetData[] = [];\n const newViewSnapshots: ViewSnapshot[] = [];\n for (const targetId of targets) {\n let targetData: TargetData;\n const queries = syncEngineImpl.queriesByTarget.get(targetId);\n\n if (queries && queries.length !== 0) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(queries[0])\n );\n\n for (const query of queries) {\n const queryView = syncEngineImpl.queryViewsByQuery.get(query);\n debugAssert(\n !!queryView,\n `No query view found for ${stringifyQuery(query)}`\n );\n\n const viewChange = await synchronizeViewAndComputeSnapshot(\n syncEngineImpl,\n queryView\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n }\n } else {\n debugAssert(\n transitionToPrimary,\n 'A secondary tab should never have an active view without an active target.'\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 localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Target for id ${targetId} not found`);\n targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target!),\n targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n }\n\n activeQueries.push(targetData!);\n }\n\n syncEngineImpl.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.\nfunction synthesizeTargetToQuery(target: Target): Query {\n return newQuery(\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/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nexport function syncEngineGetActiveClients(\n syncEngine: SyncEngine\n): Promise<ClientId[]> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return localStoreGetActiveClients(syncEngineImpl.localStore);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nexport async function syncEngineApplyTargetState(\n syncEngine: SyncEngine,\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n): Promise<void> {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n if (syncEngineImpl._isPrimaryClient) {\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 logDebug(LOG_TAG, 'Ignoring unexpected query state notification.');\n return;\n }\n\n const query = syncEngineImpl.queriesByTarget.get(targetId);\n if (query && query.length > 0) {\n switch (state) {\n case 'current':\n case 'not-current': {\n const changes = await localStoreGetNewDocumentChanges(\n syncEngineImpl.localStore,\n queryCollectionGroup(query[0])\n );\n const synthesizedRemoteEvent =\n RemoteEvent.createSynthesizedRemoteEventForCurrentChange(\n targetId,\n state === 'current',\n ByteString.EMPTY_BYTE_STRING\n );\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngineImpl,\n changes,\n synthesizedRemoteEvent\n );\n break;\n }\n case 'rejected': {\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ true\n );\n removeAndCleanupTarget(syncEngineImpl, targetId, error);\n break;\n }\n default:\n fail('Unexpected target state: ' + state);\n }\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */\nexport async function syncEngineApplyActiveTargetsChange(\n syncEngine: SyncEngine,\n added: TargetId[],\n removed: TargetId[]\n): Promise<void> {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n if (!syncEngineImpl._isPrimaryClient) {\n return;\n }\n\n for (const targetId of added) {\n if (syncEngineImpl.queriesByTarget.has(targetId)) {\n // A target might have been added in a previous attempt\n logDebug(LOG_TAG, 'Adding an already active target ' + targetId);\n continue;\n }\n\n const target = await localStoreGetCachedTarget(\n syncEngineImpl.localStore,\n targetId\n );\n debugAssert(!!target, `Query data for active target ${targetId} not found`);\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n target\n );\n await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n synthesizeTargetToQuery(target),\n targetData.targetId,\n /*current=*/ false,\n targetData.resumeToken\n );\n remoteStoreListen(syncEngineImpl.remoteStore, 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 (!syncEngineImpl.queriesByTarget.has(targetId)) {\n continue;\n }\n\n // Release queries that are still active.\n await localStoreReleaseTarget(\n syncEngineImpl.localStore,\n targetId,\n /* keepPersistedTargetData */ false\n )\n .then(() => {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId);\n removeAndCleanupTarget(syncEngineImpl, targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n}\n\nfunction ensureWatchCallbacks(syncEngine: SyncEngine): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applyRemoteEvent =\n syncEngineApplyRemoteEvent.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.getRemoteKeysForTarget =\n syncEngineGetRemoteKeysForTarget.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectListen =\n syncEngineRejectListen.bind(null, syncEngineImpl);\n syncEngineImpl.syncEngineListener.onWatchChange =\n eventManagerOnWatchChange.bind(null, syncEngineImpl.eventManager);\n syncEngineImpl.syncEngineListener.onWatchError =\n eventManagerOnWatchError.bind(null, syncEngineImpl.eventManager);\n return syncEngineImpl;\n}\n\nexport function syncEngineEnsureWriteCallbacks(\n syncEngine: SyncEngine\n): SyncEngineImpl {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.applySuccessfulWrite =\n syncEngineApplySuccessfulWrite.bind(null, syncEngineImpl);\n syncEngineImpl.remoteStore.remoteSyncer.rejectFailedWrite =\n syncEngineRejectFailedWrite.bind(null, syncEngineImpl);\n return syncEngineImpl;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */\nexport function syncEngineLoadBundle(\n syncEngine: SyncEngine,\n bundleReader: BundleReader,\n task: LoadBundleTask\n): void {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n loadBundleImpl(syncEngineImpl, bundleReader, task).then(collectionGroups => {\n syncEngineImpl.sharedClientState.notifyBundleLoaded(collectionGroups);\n });\n}\n\n/** Loads a bundle and returns the list of affected collection groups. */\nasync function loadBundleImpl(\n syncEngine: SyncEngineImpl,\n reader: BundleReader,\n task: LoadBundleTask\n): Promise<Set<string>> {\n try {\n const metadata = await reader.getMetadata();\n const skip = await localStoreHasNewerBundle(\n syncEngine.localStore,\n metadata\n );\n if (skip) {\n await reader.close();\n task._completeWith(bundleSuccessProgress(metadata));\n return Promise.resolve(new Set<string>());\n }\n\n task._updateProgress(bundleInitialProgress(metadata));\n\n const loader = new BundleLoader(\n metadata,\n syncEngine.localStore,\n reader.serializer\n );\n let element = await reader.nextElement();\n while (element) {\n debugAssert(\n !element.payload.metadata,\n 'Unexpected BundleMetadata element.'\n );\n const progress = await loader.addSizedElement(element);\n if (progress) {\n task._updateProgress(progress);\n }\n\n element = await reader.nextElement();\n }\n\n const result = await loader.complete();\n await syncEngineEmitNewSnapsAndNotifyLocalStore(\n syncEngine,\n result.changedDocs,\n /* remoteEvent */ undefined\n );\n\n // Save metadata, so loading the same bundle will skip.\n await localStoreSaveBundle(syncEngine.localStore, metadata);\n task._completeWith(result.progress);\n return Promise.resolve(result.changedCollectionGroups);\n } catch (e) {\n logWarn(LOG_TAG, `Loading bundle failed with ${e}`);\n task._failWith(e as FirestoreError);\n return Promise.resolve(new Set<string>());\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport {\n IndexBackfiller,\n IndexBackfillerScheduler\n} from '../local/index_backfiller';\nimport {\n indexedDbStoragePrefix,\n IndexedDbPersistence\n} from '../local/indexeddb_persistence';\nimport { LocalStore } from '../local/local_store';\nimport { newLocalStore } from '../local/local_store_impl';\nimport { LruParams } from '../local/lru_garbage_collector';\nimport { LruScheduler } from '../local/lru_garbage_collector_impl';\nimport {\n MemoryEagerDelegate,\n MemoryLruDelegate,\n MemoryPersistence\n} from '../local/memory_persistence';\nimport { Scheduler, Persistence } from '../local/persistence';\nimport { QueryEngine } from '../local/query_engine';\nimport {\n ClientId,\n MemorySharedClientState,\n SharedClientState,\n WebStorageSharedClientState\n} from '../local/shared_client_state';\nimport { newConnection, newConnectivityMonitor } from '../platform/connection';\nimport { getDocument, getWindow } from '../platform/dom';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport {\n fillWritePipeline,\n newRemoteStore,\n RemoteStore,\n remoteStoreApplyPrimaryState,\n remoteStoreShutdown\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { hardAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { DatabaseInfo } from './database_info';\nimport { EventManager, newEventManager } from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport {\n newSyncEngine,\n syncEngineApplyActiveTargetsChange,\n syncEngineApplyBatchState,\n syncEngineApplyOnlineStateChange,\n syncEngineApplyPrimaryState,\n syncEngineApplyTargetState,\n syncEngineEnsureWriteCallbacks,\n syncEngineGetActiveClients,\n syncEngineHandleCredentialChange,\n syncEngineSynchronizeWithChangedDocuments\n} from './sync_engine_impl';\nimport { OnlineStateSource } from './types';\n\nexport interface ComponentConfiguration {\n asyncQueue: AsyncQueue;\n databaseInfo: DatabaseInfo;\n authCredentials: CredentialsProvider<User>;\n appCheckCredentials: CredentialsProvider<string>;\n clientId: ClientId;\n initialUser: User;\n maxConcurrentLimboResolutions: number;\n}\n\n/**\n * Initializes and wires components that are needed to interface with the local\n * cache. Implementations override `initialize()` to provide all components.\n */\nexport interface OfflineComponentProvider {\n persistence: Persistence;\n sharedClientState: SharedClientState;\n localStore: LocalStore;\n gcScheduler: Scheduler | null;\n indexBackfillerScheduler: Scheduler | null;\n synchronizeTabs: boolean;\n\n initialize(cfg: ComponentConfiguration): Promise<void>;\n\n terminate(): Promise<void>;\n}\n\n/**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */\nexport class MemoryOfflineComponentProvider\n implements OfflineComponentProvider\n{\n persistence!: Persistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n serializer!: JsonProtoSerializer;\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n this.serializer = newSerializer(cfg.databaseInfo.databaseId);\n this.sharedClientState = this.createSharedClientState(cfg);\n this.persistence = this.createPersistence(cfg);\n await this.persistence.start();\n this.localStore = this.createLocalStore(cfg);\n this.gcScheduler = this.createGarbageCollectionScheduler(\n cfg,\n this.localStore\n );\n this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(\n cfg,\n this.localStore\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n return null;\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n return new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer);\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n\n async terminate(): Promise<void> {\n this.gcScheduler?.stop();\n this.indexBackfillerScheduler?.stop();\n this.sharedClientState.shutdown();\n await this.persistence.shutdown();\n }\n}\n\nexport class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider {\n constructor(protected readonly cacheSizeBytes: number | undefined) {\n super();\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n hardAssert(\n this.persistence.referenceDelegate instanceof MemoryLruDelegate,\n 'referenceDelegate is expected to be an instance of MemoryLruDelegate.'\n );\n\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createPersistence(cfg: ComponentConfiguration): Persistence {\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n return new MemoryPersistence(\n p => MemoryLruDelegate.factory(p, lruParams),\n this.serializer\n );\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */\nexport class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider {\n persistence!: IndexedDbPersistence;\n sharedClientState!: SharedClientState;\n localStore!: LocalStore;\n gcScheduler!: Scheduler | null;\n indexBackfillerScheduler!: Scheduler | null;\n synchronizeTabs = false;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined,\n protected readonly forceOwnership: boolean | undefined\n ) {\n super();\n }\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n await super.initialize(cfg);\n\n await this.onlineComponentProvider.initialize(this, cfg);\n\n // Enqueue writes from a previous session\n await syncEngineEnsureWriteCallbacks(\n this.onlineComponentProvider.syncEngine\n );\n await fillWritePipeline(this.onlineComponentProvider.remoteStore);\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(() => {\n if (this.gcScheduler && !this.gcScheduler.started) {\n this.gcScheduler.start();\n }\n if (\n this.indexBackfillerScheduler &&\n !this.indexBackfillerScheduler.started\n ) {\n this.indexBackfillerScheduler.start();\n }\n return Promise.resolve();\n });\n }\n\n createLocalStore(cfg: ComponentConfiguration): LocalStore {\n return newLocalStore(\n this.persistence,\n new QueryEngine(),\n cfg.initialUser,\n this.serializer\n );\n }\n\n createGarbageCollectionScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const garbageCollector =\n this.persistence.referenceDelegate.garbageCollector;\n return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore);\n }\n\n createIndexBackfillerScheduler(\n cfg: ComponentConfiguration,\n localStore: LocalStore\n ): Scheduler | null {\n const indexBackfiller = new IndexBackfiller(localStore, this.persistence);\n return new IndexBackfillerScheduler(cfg.asyncQueue, indexBackfiller);\n }\n\n createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence {\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n const lruParams =\n this.cacheSizeBytes !== undefined\n ? LruParams.withCacheSize(this.cacheSizeBytes)\n : LruParams.DEFAULT;\n\n return new IndexedDbPersistence(\n this.synchronizeTabs,\n persistenceKey,\n cfg.clientId,\n lruParams,\n cfg.asyncQueue,\n getWindow(),\n getDocument(),\n this.serializer,\n this.sharedClientState,\n !!this.forceOwnership\n );\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n return new MemorySharedClientState();\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */\nexport class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider {\n synchronizeTabs = true;\n\n constructor(\n protected readonly onlineComponentProvider: OnlineComponentProvider,\n protected readonly cacheSizeBytes: number | undefined\n ) {\n super(onlineComponentProvider, cacheSizeBytes, /* forceOwnership= */ false);\n }\n\n async initialize(cfg: ComponentConfiguration): Promise<void> {\n await super.initialize(cfg);\n\n const syncEngine = this.onlineComponentProvider.syncEngine;\n\n if (this.sharedClientState instanceof WebStorageSharedClientState) {\n this.sharedClientState.syncEngine = {\n applyBatchState: syncEngineApplyBatchState.bind(null, syncEngine),\n applyTargetState: syncEngineApplyTargetState.bind(null, syncEngine),\n applyActiveTargetsChange: syncEngineApplyActiveTargetsChange.bind(\n null,\n syncEngine\n ),\n getActiveClients: syncEngineGetActiveClients.bind(null, syncEngine),\n synchronizeWithChangedDocuments:\n syncEngineSynchronizeWithChangedDocuments.bind(null, syncEngine)\n };\n await this.sharedClientState.start();\n }\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 syncEngineApplyPrimaryState(\n this.onlineComponentProvider.syncEngine,\n isPrimary\n );\n if (this.gcScheduler) {\n if (isPrimary && !this.gcScheduler.started) {\n this.gcScheduler.start();\n } else if (!isPrimary) {\n this.gcScheduler.stop();\n }\n }\n if (this.indexBackfillerScheduler) {\n if (isPrimary && !this.indexBackfillerScheduler.started) {\n this.indexBackfillerScheduler.start();\n } else if (!isPrimary) {\n this.indexBackfillerScheduler.stop();\n }\n }\n });\n }\n\n createSharedClientState(cfg: ComponentConfiguration): SharedClientState {\n const window = getWindow();\n if (!WebStorageSharedClientState.isAvailable(window)) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n const persistenceKey = indexedDbStoragePrefix(\n cfg.databaseInfo.databaseId,\n cfg.databaseInfo.persistenceKey\n );\n return new WebStorageSharedClientState(\n window,\n cfg.asyncQueue,\n persistenceKey,\n cfg.clientId,\n cfg.initialUser\n );\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */\nexport class OnlineComponentProvider {\n protected localStore!: LocalStore;\n protected sharedClientState!: SharedClientState;\n datastore!: Datastore;\n eventManager!: EventManager;\n remoteStore!: RemoteStore;\n syncEngine!: SyncEngine;\n\n async initialize(\n offlineComponentProvider: OfflineComponentProvider,\n cfg: ComponentConfiguration\n ): Promise<void> {\n if (this.localStore) {\n // OnlineComponentProvider may get initialized multiple times if\n // multi-tab persistence is used.\n return;\n }\n\n this.localStore = offlineComponentProvider.localStore;\n this.sharedClientState = offlineComponentProvider.sharedClientState;\n this.datastore = this.createDatastore(cfg);\n this.remoteStore = this.createRemoteStore(cfg);\n this.eventManager = this.createEventManager(cfg);\n this.syncEngine = this.createSyncEngine(\n cfg,\n /* startAsPrimary=*/ !offlineComponentProvider.synchronizeTabs\n );\n\n this.sharedClientState.onlineStateHandler = onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.SharedClientState\n );\n\n this.remoteStore.remoteSyncer.handleCredentialChange =\n syncEngineHandleCredentialChange.bind(null, this.syncEngine);\n\n await remoteStoreApplyPrimaryState(\n this.remoteStore,\n this.syncEngine.isPrimaryClient\n );\n }\n\n createEventManager(cfg: ComponentConfiguration): EventManager {\n return newEventManager();\n }\n\n createDatastore(cfg: ComponentConfiguration): Datastore {\n const serializer = newSerializer(cfg.databaseInfo.databaseId);\n const connection = newConnection(cfg.databaseInfo);\n return newDatastore(\n cfg.authCredentials,\n cfg.appCheckCredentials,\n connection,\n serializer\n );\n }\n\n createRemoteStore(cfg: ComponentConfiguration): RemoteStore {\n return newRemoteStore(\n this.localStore,\n this.datastore,\n cfg.asyncQueue,\n onlineState =>\n syncEngineApplyOnlineStateChange(\n this.syncEngine,\n onlineState,\n OnlineStateSource.RemoteStore\n ),\n newConnectivityMonitor()\n );\n }\n\n createSyncEngine(\n cfg: ComponentConfiguration,\n startAsPrimary: boolean\n ): SyncEngine {\n return newSyncEngine(\n this.localStore,\n this.remoteStore,\n this.eventManager,\n this.sharedClientState,\n cfg.initialUser,\n cfg.maxConcurrentLimboResolutions,\n startAsPrimary\n );\n }\n\n async terminate(): Promise<void> {\n await remoteStoreShutdown(this.remoteStore);\n this.datastore?.terminate();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DatabaseInfo } from '../../core/database_info';\nimport { Connection } from '../../remote/connection';\nimport { ConnectivityMonitor } from '../../remote/connectivity_monitor';\nimport { NoopConnectivityMonitor } from '../../remote/connectivity_monitor_noop';\n\nimport { BrowserConnectivityMonitor } from './connectivity_monitor';\nimport { WebChannelConnection } from './webchannel_connection';\n\n/** Initializes the WebChannelConnection for the browser. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new WebChannelConnection(databaseInfo);\n}\n\n/** Return the Platform-specific connectivity monitor. */\nexport function newConnectivityMonitor(): ConnectivityMonitor {\n if (BrowserConnectivityMonitor.isAvailable()) {\n return new BrowserConnectivityMonitor();\n } else {\n return new NoopConnectivityMonitor();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\nexport const DEFAULT_BYTES_PER_READ = 10240;\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nexport function toByteStreamReaderHelper(\n source: Uint8Array,\n bytesPerRead: number = DEFAULT_BYTES_PER_READ\n): ReadableStreamReader<Uint8Array> {\n debugAssert(\n bytesPerRead > 0,\n `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n );\n let readFrom = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reader: any = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read(): Promise<any> {\n if (readFrom < source.byteLength) {\n const result = {\n value: source.slice(readFrom, readFrom + bytesPerRead),\n done: false\n } as const;\n readFrom += bytesPerRead;\n return result;\n }\n\n return { done: true };\n },\n async cancel(): Promise<void> {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n return reader;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Observer } from '../core/event_manager';\n\nimport { FirestoreError } from './error';\nimport { logError } from './log';\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: Partial<Observer<T>>) {}\n\n next(value: T): void {\n if (this.observer.next) {\n this.scheduleEvent(this.observer.next, value);\n }\n }\n\n error(error: FirestoreError): void {\n if (this.observer.error) {\n this.scheduleEvent(this.observer.error, error);\n } else {\n logError('Uncaught Error in snapshot listener:', error.toString());\n }\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newTextDecoder } from '../platform/text_serializer';\nimport { BundleMetadata } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\nimport { debugAssert } from './assert';\nimport { BundleReader, SizedBundleElement } from './bundle_reader';\nimport { Deferred } from './promise';\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nclass BundleReaderImpl implements BundleReader {\n /** Cached bundle metadata. */\n private metadata: Deferred<BundleMetadata> = new Deferred<BundleMetadata>();\n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n private buffer: Uint8Array = new Uint8Array();\n /** The decoder used to parse binary data into strings. */\n private textDecoder: TextDecoder;\n\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n private reader: ReadableStreamReader<Uint8Array>,\n readonly serializer: JsonProtoSerializer\n ) {\n this.textDecoder = newTextDecoder();\n // Read the metadata (which is the first element).\n this.nextElementImpl().then(\n element => {\n if (element && element.isBundleMetadata()) {\n this.metadata.resolve(element.payload.metadata!);\n } else {\n this.metadata.reject(\n new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(element?.payload)}`)\n );\n }\n },\n error => this.metadata.reject(error)\n );\n }\n\n close(): Promise<void> {\n return this.reader.cancel();\n }\n\n async getMetadata(): Promise<BundleMetadata> {\n return this.metadata.promise;\n }\n\n async nextElement(): Promise<SizedBundleElement | null> {\n // Makes sure metadata is read before proceeding.\n await this.getMetadata();\n return this.nextElementImpl();\n }\n\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */\n private async nextElementImpl(): Promise<SizedBundleElement | null> {\n const lengthBuffer = await this.readLength();\n if (lengthBuffer === null) {\n return null;\n }\n\n const lengthString = this.textDecoder.decode(lengthBuffer);\n const length = Number(lengthString);\n if (isNaN(length)) {\n this.raiseError(`length string (${lengthString}) is not valid number`);\n }\n\n const jsonString = await this.readJsonString(length);\n\n return new SizedBundleElement(\n JSON.parse(jsonString),\n lengthBuffer.length + length\n );\n }\n\n /** First index of '{' from the underlying buffer. */\n private indexOfOpenBracket(): number {\n return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n }\n\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */\n private async readLength(): Promise<Uint8Array | null> {\n while (this.indexOfOpenBracket() < 0) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n break;\n }\n }\n\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (this.buffer.length === 0) {\n return null;\n }\n\n const position = this.indexOfOpenBracket();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n if (position < 0) {\n this.raiseError(\n 'Reached the end of bundle when a length string is expected.'\n );\n }\n\n const result = this.buffer.slice(0, position);\n // Update the internal buffer to drop the read length.\n this.buffer = this.buffer.slice(position);\n return result;\n }\n\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */\n private async readJsonString(length: number): Promise<string> {\n while (this.buffer.length < length) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n this.raiseError('Reached the end of bundle when more is expected.');\n }\n }\n\n const result = this.textDecoder.decode(this.buffer.slice(0, length));\n // Update the internal buffer to drop the read json string.\n this.buffer = this.buffer.slice(length);\n return result;\n }\n\n private raiseError(message: string): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.reader.cancel();\n throw new Error(`Invalid bundle format: ${message}`);\n }\n\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */\n private async pullMoreDataToBuffer(): Promise<boolean> {\n const result = await this.reader.read();\n if (!result.done) {\n debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n const newBuffer = new Uint8Array(\n this.buffer.length + result.value!.length\n );\n newBuffer.set(this.buffer);\n newBuffer.set(result.value!, this.buffer.length);\n this.buffer = newBuffer;\n }\n return result.done;\n }\n}\n\nexport function newBundleReader(\n reader: ReadableStreamReader<Uint8Array>,\n serializer: JsonProtoSerializer\n): BundleReader {\n return new BundleReaderImpl(reader, serializer);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\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 = new Map</* path */ string, SnapshotVersion>();\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 lastTransactionError: 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</* path= */ string> = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise<Document[]> {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise<void> {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail('Document in a transaction was a ' + doc.constructor.name);\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\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.set(doc.key.toString(), 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.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\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.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\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(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\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 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner<T> {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise<T>,\n private readonly deferred: Deferred<T>\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\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 as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 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 code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logWarn } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport { Deferred } from '../util/promise';\n\nimport { Aggregate } from './aggregate';\nimport { NamedQuery } from './bundle';\nimport {\n ComponentConfiguration,\n MemoryOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from './component_provider';\nimport { DatabaseId, DatabaseInfo } from './database_info';\nimport {\n addSnapshotsInSyncListener,\n EventManager,\n eventManagerListen,\n eventManagerUnlisten,\n ListenOptions,\n Observer,\n QueryListener,\n removeSnapshotsInSyncListener\n} from './event_manager';\nimport { newQueryForPath, Query } from './query';\nimport { SyncEngine } from './sync_engine';\nimport {\n syncEngineListen,\n syncEngineLoadBundle,\n syncEngineRegisterPendingWritesCallback,\n syncEngineUnlisten,\n syncEngineWrite\n} from './sync_engine_impl';\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\nimport { TransactionRunner } from './transaction_runner';\nimport { View } from './view';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'FirestoreClient';\nexport const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100;\n\n/** DOMException error code constants. */\nconst DOM_EXCEPTION_INVALID_STATE = 11;\nconst DOM_EXCEPTION_ABORTED = 20;\nconst DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\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 private user = User.UNAUTHENTICATED;\n private readonly clientId = AutoId.newId();\n private authCredentialListener: CredentialChangeListener<User> = () =>\n Promise.resolve();\n private appCheckCredentialListener: (\n appCheckToken: string,\n user: User\n ) => Promise<void> = () => Promise.resolve();\n _uninitializedComponentsProvider?: {\n _offline: OfflineComponentProvider;\n _offlineKind: 'memory' | 'persistent';\n _online: OnlineComponentProvider;\n };\n\n _offlineComponents?: OfflineComponentProvider;\n _onlineComponents?: OnlineComponentProvider;\n\n constructor(\n private authCredentials: CredentialsProvider<User>,\n private appCheckCredentials: CredentialsProvider<string>,\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 public asyncQueue: AsyncQueue,\n private databaseInfo: DatabaseInfo\n ) {\n this.authCredentials.start(asyncQueue, async user => {\n logDebug(LOG_TAG, 'Received user=', user.uid);\n await this.authCredentialListener(user);\n this.user = user;\n });\n this.appCheckCredentials.start(asyncQueue, newAppCheckToken => {\n logDebug(LOG_TAG, 'Received new app check token=', newAppCheckToken);\n return this.appCheckCredentialListener(newAppCheckToken, this.user);\n });\n }\n\n get configuration(): ComponentConfiguration {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: MAX_CONCURRENT_LIMBO_RESOLUTIONS\n };\n }\n\n setCredentialChangeListener(listener: (user: User) => Promise<void>): void {\n this.authCredentialListener = listener;\n }\n\n setAppCheckTokenChangeListener(\n listener: (appCheckToken: string, user: User) => Promise<void>\n ): void {\n this.appCheckCredentialListener = listener;\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 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 terminate(): Promise<void> {\n this.asyncQueue.enterRestrictedMode();\n const deferred = new Deferred();\n this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n if (this._onlineComponents) {\n await this._onlineComponents.terminate();\n }\n if (this._offlineComponents) {\n await this._offlineComponents.terminate();\n }\n\n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown();\n this.appCheckCredentials.shutdown();\n deferred.resolve();\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to shutdown persistence`\n );\n deferred.reject(firestoreError);\n }\n });\n return deferred.promise;\n }\n}\n\nexport async function setOfflineComponentProvider(\n client: FirestoreClient,\n offlineComponentProvider: OfflineComponentProvider\n): Promise<void> {\n client.asyncQueue.verifyOperationInProgress();\n\n logDebug(LOG_TAG, 'Initializing OfflineComponentProvider');\n const configuration = client.configuration;\n await offlineComponentProvider.initialize(configuration);\n\n let currentUser = configuration.initialUser;\n client.setCredentialChangeListener(async user => {\n if (!currentUser.isEqual(user)) {\n await localStoreHandleUserChange(\n offlineComponentProvider.localStore,\n user\n );\n currentUser = user;\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 offlineComponentProvider.persistence.setDatabaseDeletedListener(() =>\n client.terminate()\n );\n\n client._offlineComponents = offlineComponentProvider;\n}\n\nexport async function setOnlineComponentProvider(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider\n): Promise<void> {\n client.asyncQueue.verifyOperationInProgress();\n\n const offlineComponentProvider = await ensureOfflineComponents(client);\n\n logDebug(LOG_TAG, 'Initializing OnlineComponentProvider');\n await onlineComponentProvider.initialize(\n offlineComponentProvider,\n client.configuration\n );\n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n client.setCredentialChangeListener(user =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client.setAppCheckTokenChangeListener((_, user) =>\n remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)\n );\n client._onlineComponents = onlineComponentProvider;\n}\n\n/**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\nexport function canFallbackFromIndexedDbError(\n error: FirestoreError | DOMException\n): boolean {\n if (error.name === 'FirebaseError') {\n return (\n error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED\n );\n } else if (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException\n ) {\n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n return (\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n error.code === DOM_EXCEPTION_QUOTA_EXCEEDED ||\n error.code === DOM_EXCEPTION_ABORTED ||\n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n error.code === DOM_EXCEPTION_INVALID_STATE\n );\n }\n\n return true;\n}\n\nasync function ensureOfflineComponents(\n client: FirestoreClient\n): Promise<OfflineComponentProvider> {\n if (!client._offlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OfflineComponentProvider');\n try {\n await setOfflineComponentProvider(\n client,\n client._uninitializedComponentsProvider._offline\n );\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error using user provided cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n } else {\n logDebug(LOG_TAG, 'Using default OfflineComponentProvider');\n await setOfflineComponentProvider(\n client,\n new MemoryOfflineComponentProvider()\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nasync function ensureOnlineComponents(\n client: FirestoreClient\n): Promise<OnlineComponentProvider> {\n if (!client._onlineComponents) {\n if (client._uninitializedComponentsProvider) {\n logDebug(LOG_TAG, 'Using user provided OnlineComponentProvider');\n await setOnlineComponentProvider(\n client,\n client._uninitializedComponentsProvider._online\n );\n } else {\n logDebug(LOG_TAG, 'Using default OnlineComponentProvider');\n await setOnlineComponentProvider(client, new OnlineComponentProvider());\n }\n }\n\n return client._onlineComponents!;\n}\n\nfunction getPersistence(client: FirestoreClient): Promise<Persistence> {\n return ensureOfflineComponents(client).then(c => c.persistence);\n}\n\nexport function getLocalStore(client: FirestoreClient): Promise<LocalStore> {\n return ensureOfflineComponents(client).then(c => c.localStore);\n}\n\nfunction getRemoteStore(client: FirestoreClient): Promise<RemoteStore> {\n return ensureOnlineComponents(client).then(c => c.remoteStore);\n}\n\nexport function getSyncEngine(client: FirestoreClient): Promise<SyncEngine> {\n return ensureOnlineComponents(client).then(c => c.syncEngine);\n}\n\nfunction getDatastore(client: FirestoreClient): Promise<Datastore> {\n return ensureOnlineComponents(client).then(c => c.datastore);\n}\n\nexport async function getEventManager(\n client: FirestoreClient\n): Promise<EventManager> {\n const onlineComponentProvider = await ensureOnlineComponents(client);\n const eventManager = onlineComponentProvider.eventManager;\n eventManager.onListen = syncEngineListen.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onUnlisten = syncEngineUnlisten.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n return eventManager;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */\nexport function firestoreClientEnableNetwork(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(true);\n return remoteStoreEnableNetwork(remoteStore);\n });\n}\n\n/** Disables the network connection. Pending operations will not complete. */\nexport function firestoreClientDisableNetwork(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n const persistence = await getPersistence(client);\n const remoteStore = await getRemoteStore(client);\n persistence.setNetworkEnabled(false);\n return remoteStoreDisableNetwork(remoteStore);\n });\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */\nexport function firestoreClientWaitForPendingWrites(\n client: FirestoreClient\n): Promise<void> {\n const deferred = new Deferred<void>();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineRegisterPendingWritesCallback(syncEngine, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientListen(\n client: FirestoreClient,\n query: Query,\n options: ListenOptions,\n observer: Partial<Observer<ViewSnapshot>>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n const listener = new QueryListener(query, wrappedObserver, options);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerListen(eventManager, listener);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return eventManagerUnlisten(eventManager, listener);\n });\n };\n}\n\nexport function firestoreClientGetDocumentFromLocalCache(\n client: FirestoreClient,\n docKey: DocumentKey\n): Promise<Document | null> {\n const deferred = new Deferred<Document | null>();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return readDocumentFromCache(localStore, docKey, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentViaSnapshotListener(\n client: FirestoreClient,\n key: DocumentKey,\n options: GetOptions = {}\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return readDocumentViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n key,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsFromLocalCache(\n client: FirestoreClient,\n query: Query\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const localStore = await getLocalStore(client);\n return executeQueryFromCache(localStore, query, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientGetDocumentsViaSnapshotListener(\n client: FirestoreClient,\n query: Query,\n options: GetOptions = {}\n): Promise<ViewSnapshot> {\n const deferred = new Deferred<ViewSnapshot>();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return executeQueryViaSnapshotListener(\n eventManager,\n client.asyncQueue,\n query,\n options,\n deferred\n );\n });\n return deferred.promise;\n}\n\nexport function firestoreClientRunAggregateQuery(\n client: FirestoreClient,\n query: Query,\n aggregates: Aggregate[]\n): Promise<ApiClientObjectMap<Value>> {\n const deferred = new Deferred<ApiClientObjectMap<Value>>();\n\n client.asyncQueue.enqueueAndForget(async () => {\n // Implement and call executeAggregateQueryViaSnapshotListener, similar\n // to the implementation in firestoreClientGetDocumentsViaSnapshotListener\n // above\n try {\n // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.\n const datastore = await getDatastore(client);\n deferred.resolve(\n invokeRunAggregationQueryRpc(datastore, query, aggregates)\n );\n } catch (e) {\n deferred.reject(e as Error);\n }\n });\n return deferred.promise;\n}\n\nexport function firestoreClientWrite(\n client: FirestoreClient,\n mutations: Mutation[]\n): Promise<void> {\n const deferred = new Deferred<void>();\n client.asyncQueue.enqueueAndForget(async () => {\n const syncEngine = await getSyncEngine(client);\n return syncEngineWrite(syncEngine, mutations, deferred);\n });\n return deferred.promise;\n}\n\nexport function firestoreClientAddSnapshotsInSyncListener(\n client: FirestoreClient,\n observer: Partial<Observer<void>>\n): () => void {\n const wrappedObserver = new AsyncObserver(observer);\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return addSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n return () => {\n wrappedObserver.mute();\n client.asyncQueue.enqueueAndForget(async () => {\n const eventManager = await getEventManager(client);\n return removeSnapshotsInSyncListener(eventManager, wrappedObserver);\n });\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */\nexport function firestoreClientTransaction<T>(\n client: FirestoreClient,\n updateFunction: (transaction: Transaction) => Promise<T>,\n options: TransactionOptions\n): Promise<T> {\n const deferred = new Deferred<T>();\n client.asyncQueue.enqueueAndForget(async () => {\n const datastore = await getDatastore(client);\n new TransactionRunner<T>(\n client.asyncQueue,\n datastore,\n options,\n updateFunction,\n deferred\n ).run();\n });\n return deferred.promise;\n}\n\nasync function readDocumentFromCache(\n localStore: LocalStore,\n docKey: DocumentKey,\n result: Deferred<Document | null>\n): Promise<void> {\n try {\n const document = await localStoreReadDocument(localStore, docKey);\n if (document.isFoundDocument()) {\n result.resolve(document);\n } else if (document.isNoDocument()) {\n result.resolve(null);\n } else {\n result.reject(\n 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 } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to get document '${docKey} from cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */\nfunction readDocumentViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n key: DocumentKey,\n options: GetOptions,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n const wrappedObserver = new AsyncObserver({\n next: (snap: ViewSnapshot) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n const exists = snap.docs.has(key);\n if (!exists && snap.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 result.reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document because the client is offline.'\n )\n );\n } else if (\n exists &&\n snap.fromCache &&\n options &&\n options.source === 'server'\n ) {\n result.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 debugAssert(\n snap.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n result.resolve(snap);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(\n newQueryForPath(key.path),\n wrappedObserver,\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n }\n );\n return eventManagerListen(eventManager, listener);\n}\n\nasync function executeQueryFromCache(\n localStore: LocalStore,\n query: Query,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n try {\n const queryResult = await localStoreExecuteQuery(\n localStore,\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* limboResolutionEnabled= */ false\n );\n result.resolve(viewChange.snapshot!);\n } catch (e) {\n const firestoreError = wrapInUserErrorIfRecoverable(\n e as Error,\n `Failed to execute query '${query} against cache`\n );\n result.reject(firestoreError);\n }\n}\n\n/**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */\nfunction executeQueryViaSnapshotListener(\n eventManager: EventManager,\n asyncQueue: AsyncQueue,\n query: Query,\n options: GetOptions,\n result: Deferred<ViewSnapshot>\n): Promise<void> {\n const wrappedObserver = new AsyncObserver<ViewSnapshot>({\n next: snapshot => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n asyncQueue.enqueueAndForget(() =>\n eventManagerUnlisten(eventManager, listener)\n );\n\n if (snapshot.fromCache && options.source === 'server') {\n result.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 result.resolve(snapshot);\n }\n },\n error: e => result.reject(e)\n });\n\n const listener = new QueryListener(query, wrappedObserver, {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n });\n return eventManagerListen(eventManager, listener);\n}\n\nexport function firestoreClientLoadBundle(\n client: FirestoreClient,\n databaseId: DatabaseId,\n data: ReadableStream<Uint8Array> | ArrayBuffer | string,\n resultTask: LoadBundleTask\n): void {\n const reader = createBundleReader(data, newSerializer(databaseId));\n client.asyncQueue.enqueueAndForget(async () => {\n syncEngineLoadBundle(await getSyncEngine(client), reader, resultTask);\n });\n}\n\nexport function firestoreClientGetNamedQuery(\n client: FirestoreClient,\n queryName: string\n): Promise<NamedQuery | undefined> {\n return client.asyncQueue.enqueue(async () =>\n localStoreGetNamedQuery(await getLocalStore(client), queryName)\n );\n}\n\nfunction createBundleReader(\n data: ReadableStream<Uint8Array> | ArrayBuffer | string,\n serializer: JsonProtoSerializer\n): BundleReader {\n let content: ReadableStream<Uint8Array> | ArrayBuffer;\n if (typeof data === 'string') {\n content = newTextEncoder().encode(data);\n } else {\n content = data;\n }\n return newBundleReader(toByteStreamReader(content), serializer);\n}\n\nexport function firestoreClientSetIndexConfiguration(\n client: FirestoreClient,\n indexes: FieldIndex[]\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreConfigureFieldIndexes(\n await getLocalStore(client),\n indexes\n );\n });\n}\n\nexport function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n client: FirestoreClient,\n isEnabled: boolean\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreSetIndexAutoCreationEnabled(\n await getLocalStore(client),\n isEnabled\n );\n });\n}\n\nexport function firestoreClientDeleteAllFieldIndexes(\n client: FirestoreClient\n): Promise<void> {\n return client.asyncQueue.enqueue(async () => {\n return localStoreDeleteAllFieldIndexes(await getLocalStore(client));\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleSource } from '../../util/bundle_reader';\nimport { toByteStreamReaderHelper } from '../../util/byte_stream';\n\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\nexport function toByteStreamReader(\n source: BundleSource,\n bytesPerRead: number\n): ReadableStreamReader<Uint8Array> {\n if (source instanceof Uint8Array) {\n return toByteStreamReaderHelper(source, bytesPerRead);\n }\n if (source instanceof ArrayBuffer) {\n return toByteStreamReaderHelper(new Uint8Array(source), bytesPerRead);\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n throw new Error(\n 'Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream'\n );\n}\n","/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Options that configure the SDKs underlying network transport (WebChannel)\n * when long-polling is used.\n *\n * Note: This interface is \"experimental\" and is subject to change.\n *\n * See `FirestoreSettings.experimentalAutoDetectLongPolling`,\n * `FirestoreSettings.experimentalForceLongPolling`, and\n * `FirestoreSettings.experimentalLongPollingOptions`.\n */\nexport interface ExperimentalLongPollingOptions {\n /**\n * The desired maximum timeout interval, in seconds, to complete a\n * long-polling GET response. Valid values are between 5 and 30, inclusive.\n * Floating point values are allowed and will be rounded to the nearest\n * millisecond.\n *\n * By default, when long-polling is used the \"hanging GET\" request sent by\n * the client times out after 30 seconds. To request a different timeout\n * from the server, set this setting with the desired timeout.\n *\n * Changing the default timeout may be useful, for example, if the buffering\n * proxy that necessitated enabling long-polling in the first place has a\n * shorter timeout for hanging GET requests, in which case setting the\n * long-polling timeout to a shorter value, such as 25 seconds, may fix\n * prematurely-closed hanging GET requests.\n * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.\n */\n timeoutSeconds?: number;\n}\n\n/**\n * Compares two `ExperimentalLongPollingOptions` objects for equality.\n */\nexport function longPollingOptionsEqual(\n options1: ExperimentalLongPollingOptions,\n options2: ExperimentalLongPollingOptions\n): boolean {\n return options1.timeoutSeconds === options2.timeoutSeconds;\n}\n\n/**\n * Creates and returns a new `ExperimentalLongPollingOptions` with the same\n * option values as the given instance.\n */\nexport function cloneLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): ExperimentalLongPollingOptions {\n const clone: ExperimentalLongPollingOptions = {};\n\n if (options.timeoutSeconds !== undefined) {\n clone.timeoutSeconds = options.timeoutSeconds;\n }\n\n return clone;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { _FirebaseService } from '@firebase/app';\n\nimport { CredentialsProvider } from '../api/credentials';\nimport { cloneLongPollingOptions } from '../api/long_polling_options';\nimport { User } from '../auth/user';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { newConnection } from '../platform/connection';\nimport { newSerializer } from '../platform/serializer';\nimport { Datastore, newDatastore } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug } from '../util/log';\n\nimport { FirestoreSettingsImpl } from './settings';\n\nexport const LOG_TAG = 'ComponentProvider';\n\n// The components module manages the lifetime of dependencies of the Firestore\n// client. Dependencies can be lazily constructed and only one exists per\n// Firestore instance.\n\n/**\n * An interface implemented by FirebaseFirestore that provides compatibility\n * with the usage in this file.\n *\n * This interface mainly exists to remove a cyclic dependency.\n */\nexport interface FirestoreService extends _FirebaseService {\n _authCredentials: CredentialsProvider<User>;\n _appCheckCredentials: CredentialsProvider<string>;\n _persistenceKey: string;\n _databaseId: DatabaseId;\n _terminated: boolean;\n\n _freezeSettings(): FirestoreSettingsImpl;\n}\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\nconst datastoreInstances = new Map<FirestoreService, Datastore>();\n\n/**\n * Returns an initialized and started Datastore for the given Firestore\n * instance. Callers must invoke removeComponents() when the Firestore\n * instance is terminated.\n */\nexport function getDatastore(firestore: FirestoreService): Datastore {\n if (firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!datastoreInstances.has(firestore)) {\n logDebug(LOG_TAG, 'Initializing Datastore');\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore.app.options.appId || '',\n firestore._persistenceKey,\n firestore._freezeSettings()\n );\n const connection = newConnection(databaseInfo);\n const serializer = newSerializer(firestore._databaseId);\n const datastore = newDatastore(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n connection,\n serializer\n );\n\n datastoreInstances.set(firestore, datastore);\n }\n return datastoreInstances.get(firestore)!;\n}\n\n/**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\nexport function removeComponents(firestore: FirestoreService): void {\n const datastore = datastoreInstances.get(firestore);\n if (datastore) {\n logDebug(LOG_TAG, 'Removing Datastore');\n datastoreInstances.delete(firestore);\n datastore.terminate();\n }\n}\n\nexport function makeDatabaseInfo(\n databaseId: DatabaseId,\n appId: string,\n persistenceKey: string,\n settings: FirestoreSettingsImpl\n): DatabaseInfo {\n return new DatabaseInfo(\n databaseId,\n appId,\n persistenceKey,\n settings.host,\n settings.ssl,\n settings.experimentalForceLongPolling,\n settings.experimentalAutoDetectLongPolling,\n cloneLongPollingOptions(settings.experimentalLongPollingOptions),\n settings.useFetchStreams\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\n\nimport { fail } from './assert';\nimport { Code, FirestoreError } from './error';\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\nexport function validateNonEmptyArgument(\n functionName: string,\n argumentName: string,\n argument?: string\n): asserts argument is string {\n if (!argument) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() cannot be called with an empty ${argumentName}.`\n );\n }\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */\nexport function validateIsNotUsedTogether(\n optionName1: string,\n argument1: boolean | undefined,\n optionName2: string,\n argument2: boolean | undefined\n): void {\n if (argument1 === true && argument2 === true) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `${optionName1} and ${optionName2} cannot be used together.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */\nexport function validateDocumentPath(path: ResourcePath): void {\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`\n );\n }\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */\nexport function validateCollectionPath(path: ResourcePath): void {\n if (DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`\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/** try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n return input.constructor.name;\n }\n return null;\n}\n\n/**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */\nexport function cast<T>(\n obj: object,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor: { new (...args: any[]): T }\n): T | never {\n if ('_delegate' in obj) {\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj = (obj as any)._delegate;\n }\n\n if (!(obj instanceof constructor)) {\n if (constructor.name === obj.constructor.name) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Type does not match the expected instance. Did you pass a ' +\n `reference from a different Firestore SDK?`\n );\n } else {\n const description = valueDescription(obj);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected type '${constructor.name}', but it was: ${description}`\n );\n }\n }\n return obj as T;\n}\n\nexport function validatePositiveNumber(functionName: string, n: number): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a positive number, but it was: ${n}.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreLocalCache } from '../api/cache_config';\nimport { CredentialsSettings } from '../api/credentials';\nimport {\n ExperimentalLongPollingOptions,\n cloneLongPollingOptions,\n longPollingOptionsEqual\n} from '../api/long_polling_options';\nimport {\n LRU_COLLECTION_DISABLED,\n LRU_DEFAULT_CACHE_SIZE_BYTES\n} from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { validateIsNotUsedTogether } from '../util/input_validation';\n\n// settings() defaults:\nexport const DEFAULT_HOST = 'firestore.googleapis.com';\nexport const DEFAULT_SSL = true;\n\n// The minimum long-polling timeout is hardcoded on the server. The value here\n// should be kept in sync with the value used by the server, as the server will\n// silently ignore a value below the minimum and fall back to the default.\n// Googlers see b/266868871 for relevant discussion.\nconst MIN_LONG_POLLING_TIMEOUT_SECONDS = 5;\n\n// No maximum long-polling timeout is configured in the server, and defaults to\n// 30 seconds, which is what Watch appears to use.\n// Googlers see b/266868871 for relevant discussion.\nconst MAX_LONG_POLLING_TIMEOUT_SECONDS = 30;\n\n// Whether long-polling auto-detected is enabled by default.\nconst DEFAULT_AUTO_DETECT_LONG_POLLING = true;\n\n/**\n * Specifies custom configurations for your Cloud Firestore instance.\n * You must set these before invoking any other methods.\n */\nexport interface FirestoreSettings {\n /** The hostname to connect to. */\n host?: string;\n\n /** Whether to use SSL when connecting. */\n ssl?: boolean;\n\n /**\n * Whether to skip nested properties that are set to `undefined` during\n * object serialization. If set to `true`, these properties are skipped\n * and not written to Firestore. If set to `false` or omitted, the SDK\n * throws an exception when it encounters properties of type `undefined`.\n */\n ignoreUndefinedProperties?: boolean;\n}\n\n/**\n * @internal\n * Undocumented, private additional settings not exposed in our public API.\n */\nexport interface PrivateSettings extends FirestoreSettings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n cacheSizeBytes?: number;\n experimentalForceLongPolling?: boolean;\n experimentalAutoDetectLongPolling?: boolean;\n experimentalLongPollingOptions?: ExperimentalLongPollingOptions;\n useFetchStreams?: boolean;\n\n localCache?: FirestoreLocalCache;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nexport class FirestoreSettingsImpl {\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 cacheSizeBytes: number;\n\n readonly experimentalForceLongPolling: boolean;\n\n readonly experimentalAutoDetectLongPolling: boolean;\n\n readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;\n\n readonly ignoreUndefinedProperties: boolean;\n\n readonly useFetchStreams: boolean;\n readonly localCache?: FirestoreLocalCache;\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 this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nimport {\n CredentialsProvider,\n EmulatorAuthCredentialsProvider,\n makeAuthCredentialsProvider,\n OAuthToken\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { FirestoreService, removeComponents } from './components';\nimport {\n DEFAULT_HOST,\n FirestoreSettingsImpl,\n PrivateSettings,\n FirestoreSettings\n} from './settings';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore implements FirestoreService {\n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore-lite';\n\n readonly _persistenceKey: string = '(lite)';\n\n private _settings = new FirestoreSettingsImpl({});\n private _settingsFrozen = false;\n\n // A task that is assigned when the terminate() is invoked and resolved when\n // all components have shut down.\n private _terminateTask?: Promise<void>;\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider<User>,\n public _appCheckCredentials: CredentialsProvider<string>,\n readonly _databaseId: DatabaseId,\n readonly _app?: FirebaseApp\n ) {}\n\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */\n get app(): FirebaseApp {\n if (!this._app) {\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._app;\n }\n\n get _initialized(): boolean {\n return this._settingsFrozen;\n }\n\n get _terminated(): boolean {\n return this._terminateTask !== undefined;\n }\n\n _setSettings(settings: PrivateSettings): void {\n if (this._settingsFrozen) {\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 modify settings before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n this._settings = new FirestoreSettingsImpl(settings);\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _freezeSettings(): FirestoreSettingsImpl {\n this._settingsFrozen = true;\n return this._settings;\n }\n\n _delete(): Promise<void> {\n if (!this._terminateTask) {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n /** Returns a JSON-serializable representation of this `Firestore` instance. */\n toJSON(): object {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */\n protected _terminate(): Promise<void> {\n removeComponents(this);\n return Promise.resolve();\n }\n}\n\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @returns A newly initialized `Firestore` instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings\n): Firestore;\n/**\n * Initializes a new instance of Cloud Firestore with the provided settings.\n * Can only be called before any other functions, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will\n * be associated.\n * @param settings - A settings object to configure the `Firestore` instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized `Firestore` instance.\n * @beta\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore;\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore/lite');\n\n if (provider.isInitialized(databaseId)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore can only be initialized once per app.'\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || '(default)';\n const db = _getProvider(app, 'firestore/lite').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */\nexport function connectFirestoreEmulator(\n firestore: Firestore,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n firestore = cast(firestore, Firestore);\n const settings = firestore._getSettings();\n const newHostSetting = `${host}:${port}`;\n\n if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) {\n logWarn(\n 'Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' +\n 'will be used.'\n );\n }\n\n firestore._setSettings({\n ...settings,\n host: newHostSetting,\n ssl: false\n });\n\n if (options.mockUserToken) {\n let token: string;\n let user: User;\n if (typeof options.mockUserToken === 'string') {\n token = options.mockUserToken;\n user = User.MOCK_USER;\n } else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n token = createMockUserToken(\n options.mockUserToken,\n firestore._app?.options.projectId\n );\n const uid = options.mockUserToken.sub || options.mockUserToken.user_id;\n if (!uid) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"mockUserToken must contain 'sub' or 'user_id' field!\"\n );\n }\n user = new User(uid);\n }\n\n firestore._authCredentials = new EmulatorAuthCredentialsProvider(\n new OAuthToken(token, user)\n );\n }\n}\n\n/**\n * Terminates the provided `Firestore` instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` functions\n * may be used. Any other function will throw a `FirestoreError`. Termination\n * does not cancel any pending writes, and any promises that are awaiting a\n * response from the server will not be resolved.\n *\n * To restart after termination, create a new instance of `Firestore` with\n * {@link (getFirestore:1)}.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all of\n * its resources or in combination with {@link clearIndexedDbPersistence} to\n * ensure that all local state is destroyed between test runs.\n *\n * @param firestore - The `Firestore` instance to terminate.\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n _removeServiceInstance(firestore.app, 'firestore/lite');\n return firestore._delete();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n newQueryForCollectionGroup,\n newQueryForPath,\n Query as InternalQuery,\n queryEquals\n} from '../core/query';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n cast,\n validateCollectionPath,\n validateDocumentPath,\n validateNonEmptyArgument\n} from '../util/input_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { FirestoreDataConverter } from './snapshot';\nimport { NestedUpdateFields, Primitive } from './types';\n\n/**\n * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to\n * values.\n */\nexport interface DocumentData {\n /** A mapping between a field and its value. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [field: string]: any;\n}\n\n/**\n * Similar to Typescript's `Partial<T>`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue<T> =\n | Partial<T>\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue }\n : never);\n\n/**\n * Allows FieldValues to be passed in as a property value while maintaining\n * type safety.\n */\nexport type WithFieldValue<T> =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue<T[K]> | FieldValue }\n : never);\n\n/**\n * Update data (for use with {@link (updateDoc:1)}) that consists of field paths\n * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots\n * reference nested fields within the document. FieldValues can be passed in\n * as property values.\n */\nexport type UpdateData<T> = T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData<T[K]> | FieldValue } & NestedUpdateFields<T>\n : Partial<T>;\n/**\n * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link\n * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be\n * configured to perform granular merges instead of overwriting the target\n * documents in their entirety by providing a `SetOptions` with `merge: true`.\n *\n * @param merge - Changes the behavior of a `setDoc()` call to only replace the\n * values specified in its data argument. Fields omitted from the `setDoc()`\n * call remain untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace\n * the specified field paths. Any field path that is not specified is ignored\n * and remains untouched. If your input sets any field to an empty map, all\n * nested fields are overwritten.\n */\nexport type SetOptions =\n | {\n readonly merge?: boolean;\n }\n | {\n readonly mergeFields?: Array<string | FieldPath>;\n };\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */\nexport class Query<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type: 'query' | 'collection' = 'query';\n\n /**\n * The `Firestore` instance for the Firestore database (useful for performing\n * transactions, etc.).\n */\n readonly firestore: Firestore;\n\n // This is the lite version of the Query class in the main SDK.\n\n /** @hideconstructor protected */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _query: InternalQuery\n ) {\n this.firestore = firestore;\n }\n\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `Query<DocumentData, DocumentData>` that does not use a\n * converter.\n */\n withConverter(converter: null): Query<DocumentData, DocumentData>;\n /**\n * Applies a custom data converter to this query, allowing you to use your own\n * custom model objects with Firestore. When you call {@link getDocs} with\n * the returned query, the provided converter will convert between Firestore\n * data of type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `Query` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): Query<NewAppModelType, NewDbModelType>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): Query<NewAppModelType, NewDbModelType> {\n return new Query<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._query\n );\n }\n}\n\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */\nexport class DocumentReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of this Firestore reference. */\n readonly type = 'document';\n\n /**\n * The {@link Firestore} instance the document is in.\n * This is useful for performing transactions, for example.\n */\n readonly firestore: Firestore;\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n readonly converter: FirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null,\n readonly _key: DocumentKey\n ) {\n this.firestore = firestore;\n }\n\n get _path(): ResourcePath {\n return this._key.path;\n }\n\n /**\n * The document's identifier within its collection.\n */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n /**\n * The collection this `DocumentReference` belongs to.\n */\n get parent(): CollectionReference<AppModelType, DbModelType> {\n return new CollectionReference<AppModelType, DbModelType>(\n this.firestore,\n this.converter,\n this._key.path.popLast()\n );\n }\n\n /**\n * Applies a custom data converter to this `DocumentReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`\n * instance, the provided converter will convert between Firestore data of\n * type `NewDbModelType` and your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `DocumentReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): DocumentReference<NewAppModelType, NewDbModelType>;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference<DocumentData, DocumentData>` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference<DocumentData, DocumentData>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): DocumentReference<NewAppModelType, NewDbModelType> {\n return new DocumentReference<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._key\n );\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link (query:1)}).\n */\nexport class CollectionReference<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends Query<AppModelType, DbModelType> {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter<AppModelType, DbModelType> | null,\n readonly _path: ResourcePath\n ) {\n super(firestore, converter, newQueryForPath(_path));\n }\n\n /** The collection's identifier. */\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */\n get parent(): DocumentReference<DocumentData, DocumentData> | null {\n const parentPath = this._path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(\n this.firestore,\n /* converter= */ null,\n new DocumentKey(parentPath)\n );\n }\n }\n\n /**\n * Applies a custom data converter to this `CollectionReference`, allowing you\n * to use your own custom model objects with Firestore. When you call {@link\n * addDoc} with the returned `CollectionReference` instance, the provided\n * converter will convert between Firestore data of type `NewDbModelType` and\n * your custom type `NewAppModelType`.\n *\n * @param converter - Converts objects to and from Firestore.\n * @returns A `CollectionReference` that uses the provided converter.\n */\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType>\n ): CollectionReference<NewAppModelType, NewDbModelType>;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference<DocumentData, DocumentData>` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference<DocumentData, DocumentData>;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> | null\n ): CollectionReference<NewAppModelType, NewDbModelType> {\n return new CollectionReference<NewAppModelType, NewDbModelType>(\n this.firestore,\n converter,\n this._path\n );\n }\n}\n\n/**\n * Gets a `CollectionReference` instance that refers to the collection at\n * the specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments to apply relative to the first\n * argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at the the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a collection.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an even number of segments and does not point\n * to a collection.\n * @returns The `CollectionReference` instance.\n */\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData>;\nexport function collection<AppModelType, DbModelType extends DocumentData>(\n parent:\n | Firestore\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): CollectionReference<DocumentData, DocumentData> {\n parent = getModularInstance(parent);\n\n validateNonEmptyArgument('collection', 'path', path);\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateCollectionPath(absolutePath);\n return new CollectionReference(parent, /* converter= */ null, absolutePath);\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateCollectionPath(absolutePath);\n return new CollectionReference(\n parent.firestore,\n /* converter= */ null,\n absolutePath\n );\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */\nexport function collectionGroup(\n firestore: Firestore,\n collectionId: string\n): Query<DocumentData, DocumentData> {\n firestore = cast(firestore, Firestore);\n\n validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n\n return new Query(\n firestore,\n /* converter= */ null,\n newQueryForCollectionGroup(collectionId)\n );\n}\n\n/**\n * Gets a `DocumentReference` instance that refers to the document at the\n * specified absolute path.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc(\n firestore: Firestore,\n path: string,\n ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path. If no path is specified, an\n * automatically-generated unique ID will be used for the returned\n * `DocumentReference`.\n *\n * @param reference - A reference to a collection.\n * @param path - A slash-separated path to a document. Has to be omitted to use\n * auto-genrated IDs.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType>;\n/**\n * Gets a `DocumentReference` instance that refers to a document within\n * `reference` at the specified relative path.\n *\n * @param reference - A reference to a Firestore document.\n * @param path - A slash-separated path to a document.\n * @param pathSegments - Additional path segments that will be applied relative\n * to the first argument.\n * @throws If the final path has an odd number of segments and does not point to\n * a document.\n * @returns The `DocumentReference` instance.\n */\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n path: string,\n ...pathSegments: string[]\n): DocumentReference<DocumentData, DocumentData>;\nexport function doc<AppModelType, DbModelType extends DocumentData>(\n parent:\n | Firestore\n | CollectionReference<AppModelType, DbModelType>\n | DocumentReference<AppModelType, DbModelType>,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference<AppModelType, DbModelType> {\n parent = getModularInstance(parent);\n\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 1) {\n path = AutoId.newId();\n }\n validateNonEmptyArgument('doc', 'path', path);\n\n if (parent instanceof Firestore) {\n const absolutePath = ResourcePath.fromString(path, ...pathSegments);\n validateDocumentPath(absolutePath);\n return new DocumentReference(\n parent,\n /* converter= */ null,\n new DocumentKey(absolutePath)\n );\n } else {\n if (\n !(parent instanceof DocumentReference) &&\n !(parent instanceof CollectionReference)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Expected first argument to collection() to be a CollectionReference, ' +\n 'a DocumentReference or FirebaseFirestore'\n );\n }\n const absolutePath = parent._path.child(\n ResourcePath.fromString(path, ...pathSegments)\n );\n validateDocumentPath(absolutePath);\n return new DocumentReference<AppModelType, DbModelType>(\n parent.firestore,\n parent instanceof CollectionReference ? parent.converter : null,\n new DocumentKey(absolutePath)\n );\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function refEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>,\n right:\n | DocumentReference<AppModelType, DbModelType>\n | CollectionReference<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (\n (left instanceof DocumentReference ||\n left instanceof CollectionReference) &&\n (right instanceof DocumentReference || right instanceof CollectionReference)\n ) {\n return (\n left.firestore === right.firestore &&\n left.path === right.path &&\n left.converter === right.converter\n );\n }\n return false;\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */\nexport function queryEqual<AppModelType, DbModelType extends DocumentData>(\n left: Query<AppModelType, DbModelType>,\n right: Query<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof Query && right instanceof Query) {\n return (\n left.firestore === right.firestore &&\n queryEquals(left._query, right._query) &&\n left.converter === right.converter\n );\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIndexedDbTransactionError } from '../local/simple_db';\nimport { getDocument } from '../platform/dom';\nimport { ExponentialBackoff } from '../remote/backoff';\n\nimport { debugAssert, fail } from './assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from './async_queue';\nimport { FirestoreError } from './error';\nimport { logDebug, logError } from './log';\nimport { Deferred } from './promise';\n\nconst LOG_TAG = 'AsyncQueue';\n\nexport class AsyncQueueImpl implements AsyncQueue {\n // The last promise in the queue.\n private tail: Promise<unknown> = Promise.resolve();\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise<void>> = [];\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: FirestoreError | 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 // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n private skipNonRestrictedTasks = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Backoff timer used to schedule retries for retryable operations\n private backoff = new ExponentialBackoff(this, TimerId.AsyncQueueRetry);\n\n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n private visibilityHandler: () => void = () => {\n const document = getDocument();\n if (document) {\n logDebug(\n LOG_TAG,\n 'Visibility state changed to ' + document.visibilityState\n );\n }\n this.backoff.skipBackoff();\n };\n\n constructor() {\n const document = getDocument();\n if (document && typeof document.addEventListener === 'function') {\n document.addEventListener('visibilitychange', this.visibilityHandler);\n }\n }\n\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 enqueueAndForgetEvenWhileRestricted<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 enterRestrictedMode(purgeExistingTasks?: boolean): void {\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n this.skipNonRestrictedTasks = purgeExistingTasks || false;\n const document = getDocument();\n if (document && typeof document.removeEventListener === 'function') {\n document.removeEventListener(\n 'visibilitychange',\n this.visibilityHandler\n );\n }\n }\n }\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>(() => {});\n }\n\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const task = new Deferred<T>();\n return this.enqueueInternal<unknown>(() => {\n if (this._isShuttingDown && this.skipNonRestrictedTasks) {\n // We do not resolve 'task'\n return Promise.resolve();\n }\n\n op().then(task.resolve, task.reject);\n return task.promise;\n }).then(() => task.promise);\n }\n\n enqueueRetryable(op: () => Promise<void>): void {\n this.enqueueAndForget(() => {\n this.retryableOps.push(op);\n return this.retryNextOp();\n });\n }\n\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */\n private async retryNextOp(): Promise<void> {\n if (this.retryableOps.length === 0) {\n return;\n }\n\n try {\n await this.retryableOps[0]();\n this.retryableOps.shift();\n this.backoff.reset();\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);\n } else {\n throw e; // Failure will be handled by AsyncQueue\n }\n }\n\n if (this.retryableOps.length > 0) {\n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.backoff.backoffAndRun(() => this.retryNextOp());\n }\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 = getMessageOrStack(error);\n logError('INTERNAL UNHANDLED ERROR: ', message);\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 enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): DelayedOperation<T> {\n this.verifyNotFailed();\n\n debugAssert(\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('AsyncQueue is already failed: ' + getMessageOrStack(this.failure));\n }\n }\n\n verifyOperationInProgress(): void {\n debugAssert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise<void> {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise<unknown>;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise<void> {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\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 debugAssert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n }\n}\n\nexport function newAsyncQueue(): AsyncQueue {\n return new AsyncQueueImpl();\n}\n\n/**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\nfunction getMessageOrStack(error: Error): string {\n let message = error.message || '';\n if (error.stack) {\n if (error.stack.includes(error.message)) {\n message = error.stack;\n } else {\n message = error.message + '\\n' + error.stack;\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => 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 function isPartialObserver<T>(obj: unknown): obj is PartialObserver<T> {\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PartialObserver } from '../api/observer';\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\n\n/**\n * Represents the state of bundle loading tasks.\n *\n * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will\n * be no more updates after they are reported.\n */\nexport type TaskState = 'Error' | 'Running' | 'Success';\n\n/**\n * Represents a progress update or a final state from loading bundles.\n */\nexport interface LoadBundleTaskProgress {\n /** How many documents have been loaded. */\n documentsLoaded: number;\n /** How many documents are in the bundle being loaded. */\n totalDocuments: number;\n /** How many bytes have been loaded. */\n bytesLoaded: number;\n /** How many bytes are in the bundle being loaded. */\n totalBytes: number;\n /** Current task state. */\n taskState: TaskState;\n}\n\n/**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise<LoadBundleTaskProgress>`.\n */\nexport class LoadBundleTask implements PromiseLike<LoadBundleTaskProgress> {\n private _progressObserver: PartialObserver<LoadBundleTaskProgress> = {};\n private _taskCompletionResolver = new Deferred<LoadBundleTaskProgress>();\n\n private _lastProgress: LoadBundleTaskProgress = {\n taskState: 'Running',\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */\n onProgress(\n next?: (progress: LoadBundleTaskProgress) => unknown,\n error?: (err: Error) => unknown,\n complete?: () => void\n ): void {\n this._progressObserver = {\n next,\n error,\n complete\n };\n }\n\n /**\n * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n catch<R>(\n onRejected: (a: Error) => R | PromiseLike<R>\n ): Promise<R | LoadBundleTaskProgress> {\n return this._taskCompletionResolver.promise.catch(onRejected);\n }\n\n /**\n * Implements the `Promise<LoadBundleTaskProgress>.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n then<T, R>(\n onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike<T>,\n onRejected?: (a: Error) => R | PromiseLike<R>\n ): Promise<T | R> {\n return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n }\n\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */\n _completeWith(progress: LoadBundleTaskProgress): void {\n debugAssert(\n progress.taskState === 'Success',\n 'Task is not completed with Success.'\n );\n this._updateProgress(progress);\n if (this._progressObserver.complete) {\n this._progressObserver.complete();\n }\n\n this._taskCompletionResolver.resolve(progress);\n }\n\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */\n _failWith(error: FirestoreError): void {\n this._lastProgress.taskState = 'Error';\n\n if (this._progressObserver.next) {\n this._progressObserver.next(this._lastProgress);\n }\n\n if (this._progressObserver.error) {\n this._progressObserver.error(error);\n }\n\n this._taskCompletionResolver.reject(error);\n }\n\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */\n _updateProgress(progress: LoadBundleTaskProgress): void {\n debugAssert(\n this._lastProgress.taskState === 'Running',\n 'Cannot update progress on a completed or failed task'\n );\n\n this._lastProgress = progress;\n if (this._progressObserver.next) {\n this._progressObserver.next(progress);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport { deepEqual, getDefaultEmulatorHostnameAndPort } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport {\n IndexedDbOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProvider,\n OnlineComponentProvider\n} from '../core/component_provider';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport {\n canFallbackFromIndexedDbError,\n FirestoreClient,\n firestoreClientDisableNetwork,\n firestoreClientEnableNetwork,\n firestoreClientGetNamedQuery,\n firestoreClientLoadBundle,\n firestoreClientWaitForPendingWrites,\n setOfflineComponentProvider,\n setOnlineComponentProvider\n} from '../core/firestore_client';\nimport { makeDatabaseInfo } from '../lite-api/components';\nimport {\n Firestore as LiteFirestore,\n connectFirestoreEmulator\n} from '../lite-api/database';\nimport { Query } from '../lite-api/reference';\nimport {\n indexedDbClearPersistence,\n indexedDbStoragePrefix\n} from '../local/indexeddb_persistence';\nimport { LRU_COLLECTION_DISABLED } from '../local/lru_garbage_collector';\nimport { LRU_MINIMUM_CACHE_SIZE_BYTES } from '../local/lru_garbage_collector_impl';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\nimport { Deferred } from '../util/promise';\n\nimport { LoadBundleTask } from './bundle';\nimport { CredentialsProvider } from './credentials';\nimport { PersistenceSettings, FirestoreSettings } from './settings';\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\n }\n}\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 * {@link Firestore} instance.\n */\nexport const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nexport class Firestore extends LiteFirestore {\n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n type: 'firestore-lite' | 'firestore' = 'firestore';\n\n readonly _queue: AsyncQueue = newAsyncQueue();\n readonly _persistenceKey: string;\n\n _firestoreClient: FirestoreClient | undefined;\n\n /** @hideconstructor */\n constructor(\n authCredentialsProvider: CredentialsProvider<User>,\n appCheckCredentialsProvider: CredentialsProvider<string>,\n databaseId: DatabaseId,\n app?: FirebaseApp\n ) {\n super(\n authCredentialsProvider,\n appCheckCredentialsProvider,\n databaseId,\n app\n );\n this._persistenceKey = app?.name || '[DEFAULT]';\n }\n\n _terminate(): Promise<void> {\n if (!this._firestoreClient) {\n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n configureFirestore(this);\n }\n return this._firestoreClient!.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of the database.\n * @returns A newly initialized {@link Firestore} instance.\n */\nexport function initializeFirestore(\n app: FirebaseApp,\n settings: FirestoreSettings,\n databaseId?: string\n): Firestore {\n if (!databaseId) {\n databaseId = DEFAULT_DATABASE_NAME;\n }\n const provider = _getProvider(app, 'firestore');\n\n if (provider.isInitialized(databaseId)) {\n const existingInstance = provider.getImmediate({\n identifier: databaseId\n });\n const initialSettings = provider.getOptions(\n databaseId\n ) as FirestoreSettings;\n if (deepEqual(initialSettings, settings)) {\n return existingInstance;\n } else {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'initializeFirestore() has already been called with ' +\n 'different options. To avoid this error, call initializeFirestore() with the ' +\n 'same options as when it was originally called, or call getFirestore() to return the' +\n ' already initialized instance.'\n );\n }\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.localCache !== undefined\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes will` +\n `be deprecated. Instead, specify the cache size in the cache object`\n );\n }\n\n if (\n settings.cacheSizeBytes !== undefined &&\n settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n }\n\n return provider.initialize({\n options: settings,\n instanceIdentifier: databaseId\n });\n}\n\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @returns The default {@link Firestore} instance of the default app.\n */\nexport function getFirestore(): Firestore;\n/**\n * Returns the existing default {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The default {@link Firestore} instance of the provided app.\n */\nexport function getFirestore(app: FirebaseApp): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the default app.\n * @beta\n */\nexport function getFirestore(databaseId: string): Firestore;\n/**\n * Returns the existing named {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @param databaseId - The name of the database.\n * @returns The named {@link Firestore} instance of the provided app.\n * @beta\n */\nexport function getFirestore(app: FirebaseApp, databaseId: string): Firestore;\nexport function getFirestore(\n appOrDatabaseId?: FirebaseApp | string,\n optionalDatabaseId?: string\n): Firestore {\n const app: FirebaseApp =\n typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();\n const databaseId =\n typeof appOrDatabaseId === 'string'\n ? appOrDatabaseId\n : optionalDatabaseId || DEFAULT_DATABASE_NAME;\n const db = _getProvider(app, 'firestore').getImmediate({\n identifier: databaseId\n }) as Firestore;\n if (!db._initialized) {\n const emulator = getDefaultEmulatorHostnameAndPort('firestore');\n if (emulator) {\n connectFirestoreEmulator(db, ...emulator);\n }\n }\n return db;\n}\n\n/**\n * @internal\n */\nexport function ensureFirestoreConfigured(\n firestore: Firestore\n): FirestoreClient {\n if (!firestore._firestoreClient) {\n configureFirestore(firestore);\n }\n firestore._firestoreClient!.verifyNotTerminated();\n return firestore._firestoreClient as FirestoreClient;\n}\n\nexport function configureFirestore(firestore: Firestore): void {\n const settings = firestore._freezeSettings();\n debugAssert(!!settings.host, 'FirestoreSettings.host is not set');\n debugAssert(\n !firestore._firestoreClient,\n 'configureFirestore() called multiple times'\n );\n\n const databaseInfo = makeDatabaseInfo(\n firestore._databaseId,\n firestore._app?.options.appId || '',\n firestore._persistenceKey,\n settings\n );\n firestore._firestoreClient = new FirestoreClient(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n firestore._queue,\n databaseInfo\n );\n if (\n settings.localCache?._offlineComponentProvider &&\n settings.localCache?._onlineComponentProvider\n ) {\n firestore._firestoreClient._uninitializedComponentsProvider = {\n _offlineKind: settings.localCache.kind,\n _offline: settings.localCache._offlineComponentProvider,\n _online: settings.localCache._onlineComponentProvider\n };\n }\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * On failure, `enableIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * Note: `enableIndexedDbPersistence()` must be called before any other functions\n * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * Persistence cannot be used in a Node.js environment.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableIndexedDbPersistence(\n firestore: Firestore,\n persistenceSettings?: PersistenceSettings\n): Promise<void> {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new IndexedDbOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes,\n persistenceSettings?.forceOwnership\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or\n * throw an exception. There are several reasons why this can fail, which can be\n * identified by the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline persistence\n * implementation.\n *\n * Note that even after a failure, the {@link Firestore} instance will remain\n * usable, however offline persistence will be disabled.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n * @deprecated This function will be removed in a future major release. Instead, set\n * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to\n * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`\n * is already specified will throw an exception.\n */\nexport function enableMultiTabIndexedDbPersistence(\n firestore: Firestore\n): Promise<void> {\n firestore = cast(firestore, Firestore);\n verifyNotInitialized(firestore);\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n logWarn(\n 'enableMultiTabIndexedDbPersistence() will be deprecated in the future, ' +\n 'you can use `FirestoreSettings.cache` instead.'\n );\n const settings = firestore._freezeSettings();\n\n const onlineComponentProvider = new OnlineComponentProvider();\n const offlineComponentProvider = new MultiTabOfflineComponentProvider(\n onlineComponentProvider,\n settings.cacheSizeBytes\n );\n return setPersistenceProviders(\n client,\n onlineComponentProvider,\n offlineComponentProvider\n );\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */\nfunction setPersistenceProviders(\n client: FirestoreClient,\n onlineComponentProvider: OnlineComponentProvider,\n offlineComponentProvider: OfflineComponentProvider\n): Promise<void> {\n const persistenceResult = new Deferred();\n return client.asyncQueue\n .enqueue(async () => {\n try {\n await setOfflineComponentProvider(client, offlineComponentProvider);\n await setOnlineComponentProvider(client, onlineComponentProvider);\n persistenceResult.resolve();\n } catch (e) {\n const error = e as FirestoreError | DOMException;\n if (!canFallbackFromIndexedDbError(error)) {\n throw error;\n }\n logWarn(\n 'Error enabling indexeddb cache. Falling back to ' +\n 'memory cache: ' +\n error\n );\n persistenceResult.reject(error);\n }\n })\n .then(() => persistenceResult.promise);\n}\n\n/**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */\nexport function clearIndexedDbPersistence(firestore: Firestore): Promise<void> {\n if (firestore._initialized && !firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Persistence can only be cleared before a Firestore instance is ' +\n 'initialized or after it is terminated.'\n );\n }\n\n const deferred = new Deferred<void>();\n firestore._queue.enqueueAndForgetEvenWhileRestricted(async () => {\n try {\n await indexedDbClearPersistence(\n indexedDbStoragePrefix(firestore._databaseId, firestore._persistenceKey)\n );\n deferred.resolve();\n } catch (e) {\n deferred.reject(e as Error | undefined);\n }\n });\n return deferred.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */\nexport function waitForPendingWrites(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWaitForPendingWrites(client);\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */\nexport function enableNetwork(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientEnableNetwork(client);\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */\nexport function disableNetwork(firestore: Firestore): Promise<void> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientDisableNetwork(client);\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */\nexport function terminate(firestore: Firestore): Promise<void> {\n _removeServiceInstance(\n firestore.app,\n 'firestore',\n firestore._databaseId.database\n );\n return firestore._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise<LoadBundleTaskProgress>`.\n */\nexport function loadBundle(\n firestore: Firestore,\n bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string\n): LoadBundleTask {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const resultTask = new LoadBundleTask();\n firestoreClientLoadBundle(\n client,\n firestore._databaseId,\n bundleData,\n resultTask\n );\n return resultTask;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */\nexport function namedQuery(\n firestore: Firestore,\n name: string\n): Promise<Query | null> {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientGetNamedQuery(client, name).then(namedQuery => {\n if (!namedQuery) {\n return null;\n }\n\n return new Query(firestore, null, namedQuery.query);\n });\n}\n\nfunction verifyNotInitialized(firestore: Firestore): void {\n if (firestore._initialized || firestore._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and persistence can no longer be ' +\n 'enabled. You can only enable persistence before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\nimport {\n FirebaseAppCheckTokenProvider,\n FirebaseAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { setSDKVersion } from '../src/core/version';\n\nimport { Firestore } from './api/database';\nimport { databaseIdFromApp } from './core/database_info';\n\nexport function registerFirestore(\n variant?: string,\n useFetchStreams = true\n): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n 'firestore',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new FirebaseAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new FirebaseAppCheckTokenProvider(\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n settings = { useFetchStreams, ...settings };\n firestoreInstance._setSettings(settings);\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app-compat';\nimport type { FirebaseNamespace } from '@firebase/app-types';\nimport * as types from '@firebase/firestore-types';\n\nimport { name, version } from '../package.json';\n\nimport { Firestore, IndexedDbPersistenceProvider } from './api/database';\nimport { configureForFirebase } from './config';\n\nimport './register-module';\n\n/**\n * Registers the main Firestore build with the components framework.\n * Persistence can be enabled via `firebase.firestore().enablePersistence()`.\n */\nexport function registerFirestore(instance: FirebaseNamespace): void {\n configureForFirebase(\n instance,\n (app, firestoreExp) =>\n new Firestore(app, firestoreExp, new IndexedDbPersistenceProvider())\n );\n instance.registerVersion(name, version);\n}\n\nregisterFirestore(firebase as unknown as FirebaseNamespace);\n\ndeclare module '@firebase/app-compat' {\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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { FirebaseApp } from '@firebase/app-compat';\nimport { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport {\n Firestore as ModularFirestore,\n CACHE_SIZE_UNLIMITED,\n GeoPoint,\n Timestamp\n} from '@firebase/firestore';\n\nimport { Blob } from './api/blob';\nimport {\n Firestore,\n Transaction,\n CollectionReference,\n DocumentReference,\n DocumentSnapshot,\n Query,\n QueryDocumentSnapshot,\n QuerySnapshot,\n WriteBatch,\n setLogLevel\n} from './api/database';\nimport { FieldPath } from './api/field_path';\nimport { FieldValue } from './api/field_value';\n\nconst firestoreNamespace = {\n Firestore,\n GeoPoint,\n Timestamp,\n Blob,\n Transaction,\n WriteBatch,\n DocumentReference,\n DocumentSnapshot,\n Query,\n QueryDocumentSnapshot,\n QuerySnapshot,\n CollectionReference,\n FieldPath,\n FieldValue,\n setLogLevel,\n CACHE_SIZE_UNLIMITED\n};\n\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerComponent.\n *\n * @param firebase - The FirebaseNamespace to register Firestore with\n * @param firestoreFactory - A factory function that returns a new Firestore\n * instance.\n */\nexport function configureForFirebase(\n firebase: FirebaseNamespace,\n firestoreFactory: (\n app: FirebaseApp,\n firestoreExp: ModularFirestore\n ) => Firestore\n): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'firestore-compat',\n container => {\n const app = container.getProvider('app-compat').getImmediate()!;\n const firestoreExp = container.getProvider('firestore').getImmediate()!;\n return firestoreFactory(app, firestoreExp);\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setServiceProps({ ...firestoreNamespace })\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport { FunctionsService } from './service';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactory\n} from '@firebase/component';\nimport { FUNCTIONS_TYPE } from './constants';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { MessagingInternalComponentName } from '@firebase/messaging-interop-types';\nimport { name, version } from '../package.json';\n\nconst AUTH_INTERNAL_NAME: FirebaseAuthInternalName = 'auth-internal';\nconst APP_CHECK_INTERNAL_NAME: AppCheckInternalComponentName =\n 'app-check-internal';\nconst MESSAGING_INTERNAL_NAME: MessagingInternalComponentName =\n 'messaging-internal';\n\nexport function registerFunctions(\n fetchImpl: typeof fetch,\n variant?: string\n): void {\n const factory: InstanceFactory<'functions'> = (\n container: ComponentContainer,\n { instanceIdentifier: regionOrCustomDomain }\n ) => {\n // Dependencies\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider(AUTH_INTERNAL_NAME);\n const messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);\n const appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new FunctionsService(\n app,\n authProvider,\n messagingProvider,\n appCheckProvider,\n regionOrCustomDomain,\n fetchImpl\n );\n };\n\n _registerComponent(\n new Component(\n FUNCTIONS_TYPE,\n factory,\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n\n registerVersion(name, version, variant);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * An immutable object representing an array of bytes.\n */\nexport class Bytes {\n _byteString: ByteString;\n\n /** @hideconstructor */\n constructor(byteString: ByteString) {\n this._byteString = byteString;\n }\n\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */\n static fromBase64String(base64: string): Bytes {\n try {\n return new Bytes(ByteString.fromBase64String(base64));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct data from Base64 string: ' + e\n );\n }\n }\n\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */\n static fromUint8Array(array: Uint8Array): Bytes {\n return new Bytes(ByteString.fromUint8Array(array));\n }\n\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */\n toBase64(): string {\n return this._byteString.toBase64();\n }\n\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */\n toUint8Array(): Uint8Array {\n return this._byteString.toUint8Array();\n }\n\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */\n toString(): string {\n return 'Bytes(base64: ' + this.toBase64() + ')';\n }\n\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */\n isEqual(other: Bytes): boolean {\n return this._byteString.isEqual(other._byteString);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DOCUMENT_KEY_NAME,\n FieldPath as InternalFieldPath\n} from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nexport class FieldPath {\n /** Internal representation of a Firestore field path. */\n readonly _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 for (let i = 0; i < fieldNames.length; ++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 * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */\n isEqual(other: FieldPath): boolean {\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */\nexport function documentId(): FieldPath {\n return new FieldPath(DOCUMENT_KEY_NAME);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParseContext } from '../api/parse_context';\nimport { FieldTransform } from '../model/mutation';\n\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */\nexport abstract class FieldValue {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(public _methodName: string) {}\n\n /** Compares `FieldValue`s for equality. */\n abstract isEqual(other: FieldValue): boolean;\n abstract _toFieldTransform(context: ParseContext): FieldTransform | null;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */\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 /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(latitude: number, longitude: number) {\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 * The latitude of this `GeoPoint` instance.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * The longitude of this `GeoPoint` instance.\n */\n get longitude(): number {\n return this._long;\n }\n\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /** Returns a JSON-serializable representation of this GeoPoint. */\n toJSON(): { latitude: number; longitude: number } {\n return { latitude: this._lat, longitude: this._long };\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toNumber } from '../remote/number_serializer';\nimport {\n JsonProtoSerializer,\n toBytes,\n toResourceName,\n toTimestamp\n} from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { Dict, forEach, isEmpty } from '../util/obj';\n\nimport { Bytes } from './bytes';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { FieldValue } from './field_value';\nimport { GeoPoint } from './geo_point';\nimport {\n DocumentReference,\n PartialWithFieldValue,\n WithFieldValue\n} from './reference';\nimport { Timestamp } from './timestamp';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/**\n * An untyped Firestore Data Converter interface that is shared between the\n * lite, firestore-exp and classic SDK.\n */\nexport interface UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n fromFirestore(snapshot: unknown, options?: unknown): AppModelType;\n}\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 toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n if (this.fieldMask !== null) {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\n } else {\n return new SetMutation(\n key,\n this.data,\n precondition,\n this.fieldTransforms\n );\n }\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 // The fieldMask does not include document transforms.\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutation(key: DocumentKey, precondition: Precondition): Mutation {\n return new PatchMutation(\n key,\n this.data,\n this.fieldMask,\n precondition,\n this.fieldTransforms\n );\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 */\nexport const enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** Contains the settings that are mutated as we parse user data. */\ninterface ContextSettings {\n /** Indicates what kind of API method this data came from. */\n readonly dataSource: UserDataSource;\n /** The name of the method the user called to create the ParseContext. */\n readonly methodName: string;\n /** The document the user is attempting to modify, if that applies. */\n readonly targetDoc?: DocumentKey;\n /**\n * A path within the object being parsed. This could be an empty path (in\n * which case the context represents the root of the data being parsed), or a\n * nonempty path (indicating the context represents a nested location within\n * the data).\n */\n readonly path?: InternalFieldPath;\n /**\n * Whether or not this context corresponds to an element of an array.\n * If not set, elements are treated as if they were outside of arrays.\n */\n readonly arrayElement?: boolean;\n /**\n * Whether or not a converter was specified in this context. If true, error\n * messages will reference the converter when invalid data is provided.\n */\n readonly hasConverter?: boolean;\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContextImpl implements ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: InternalFieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly settings: ContextSettings,\n readonly databaseId: DatabaseId,\n readonly serializer: JsonProtoSerializer,\n readonly ignoreUndefinedProperties: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: InternalFieldPath[]\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.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n get path(): InternalFieldPath | undefined {\n return this.settings.path;\n }\n\n get dataSource(): UserDataSource {\n return this.settings.dataSource;\n }\n\n /** Returns a new context with the specified settings overwritten. */\n contextWith(configuration: Partial<ContextSettings>): ParseContextImpl {\n return new ParseContextImpl(\n { ...this.settings, ...configuration },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n childContextForField(field: string): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: InternalFieldPath): ParseContextImpl {\n const childPath = this.path?.child(field);\n const context = this.contextWith({ path: childPath, arrayElement: false });\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContextImpl {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.contextWith({ path: undefined, arrayElement: true });\n }\n\n createError(reason: string): FirestoreError {\n return createError(\n reason,\n this.settings.methodName,\n this.settings.hasConverter || false,\n this.path,\n this.settings.targetDoc\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: InternalFieldPath): 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) {\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/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataReader {\n private readonly serializer: JsonProtoSerializer;\n\n constructor(\n private readonly databaseId: DatabaseId,\n private readonly ignoreUndefinedProperties: boolean,\n serializer?: JsonProtoSerializer\n ) {\n this.serializer = serializer || newSerializer(databaseId);\n }\n\n /** Creates a new top-level parse context. */\n createContext(\n dataSource: UserDataSource,\n methodName: string,\n targetDoc?: DocumentKey,\n hasConverter = false\n ): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource,\n methodName,\n targetDoc,\n path: InternalFieldPath.emptyPath(),\n arrayElement: false,\n hasConverter\n },\n this.databaseId,\n this.serializer,\n this.ignoreUndefinedProperties\n );\n }\n}\n\nexport function newUserDataReader(firestore: Firestore): UserDataReader {\n const settings = firestore._freezeSettings();\n const serializer = newSerializer(firestore._databaseId);\n return new UserDataReader(\n firestore._databaseId,\n !!settings.ignoreUndefinedProperties,\n serializer\n );\n}\n\n/** Parse document data from a set() call. */\nexport function parseSetData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown,\n hasConverter: boolean,\n options: SetOptions = {}\n): ParsedSetData {\n const context = userDataReader.createContext(\n options.merge || options.mergeFields\n ? UserDataSource.MergeSet\n : UserDataSource.Set,\n methodName,\n targetDoc,\n hasConverter\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n const updateData = parseObject(input, context)!;\n\n let fieldMask: FieldMask | null;\n let fieldTransforms: FieldTransform[];\n\n if (options.merge) {\n fieldMask = new FieldMask(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else if (options.mergeFields) {\n const validatedFieldPaths: InternalFieldPath[] = [];\n\n for (const stringOrFieldPath of options.mergeFields) {\n const fieldPath = fieldPathFromArgument(\n methodName,\n stringOrFieldPath,\n targetDoc\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 if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {\n validatedFieldPaths.push(fieldPath);\n }\n }\n\n fieldMask = new FieldMask(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask!.covers(transform.field)\n );\n } else {\n fieldMask = null;\n fieldTransforms = context.fieldTransforms;\n }\n\n return new ParsedSetData(\n new ObjectValue(updateData),\n fieldMask,\n fieldTransforms\n );\n}\n\nexport class DeleteFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): null {\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 debugAssert(\n context.path!.length > 0,\n `${this._methodName}() at the top level should have already ` +\n 'been handled.'\n );\n throw context.createError(\n `${this._methodName}() 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 `${this._methodName}() cannot be used with set() unless you pass ` +\n '{merge:true}'\n );\n }\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof DeleteFieldValueImpl;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */\nfunction createSentinelChildContext(\n fieldValue: FieldValue,\n context: ParseContextImpl,\n arrayElement: boolean\n): ParseContextImpl {\n return new ParseContextImpl(\n {\n dataSource: UserDataSource.Argument,\n targetDoc: context.settings.targetDoc,\n methodName: fieldValue._methodName,\n arrayElement\n },\n context.databaseId,\n context.serializer,\n context.ignoreUndefinedProperties\n );\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValue {\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n return new FieldTransform(context.path!, new ServerTimestampTransform());\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof ServerTimestampFieldValueImpl;\n }\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayUnionFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _elements: unknown[]) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const parseContext = createSentinelChildContext(\n this,\n context,\n /*array=*/ true\n );\n const parsedElements = this._elements.map(\n element => parseData(element, parseContext)!\n );\n const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);\n return new FieldTransform(context.path!, arrayUnion);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ArrayRemoveFieldValueImpl &&\n deepEqual(this._elements, other._elements)\n );\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValue {\n constructor(methodName: string, private readonly _operand: number) {\n super(methodName);\n }\n\n _toFieldTransform(context: ParseContextImpl): FieldTransform {\n const numericIncrement = new NumericIncrementTransformOperation(\n context.serializer,\n toNumber(context.serializer, this._operand)\n );\n return new FieldTransform(context.path!, numericIncrement);\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof NumericIncrementFieldValueImpl &&\n this._operand === other._operand\n );\n }\n}\n\n/** Parse update data from an update() call. */\nexport function parseUpdateData(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n input: unknown\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n forEach(input as Dict<unknown>, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = new FieldMask(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */\nexport function parseUpdateVarargs(\n userDataReader: UserDataReader,\n methodName: string,\n targetDoc: DocumentKey,\n field: string | PublicFieldPath | Compat<PublicFieldPath>,\n value: unknown,\n moreFieldsAndValues: unknown[]\n): ParsedUpdateData {\n const context = userDataReader.createContext(\n UserDataSource.Update,\n methodName,\n targetDoc\n );\n const keys = [fieldPathFromArgument(methodName, field, targetDoc)];\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 | PublicFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n const fieldMaskPaths: InternalFieldPath[] = [];\n const updateData = ObjectValue.empty();\n\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let i = keys.length - 1; i >= 0; --i) {\n if (!fieldMaskContains(fieldMaskPaths, keys[i])) {\n const path = keys[i];\n let value = values[i];\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n value = getModularInstance(value);\n\n const childContext = context.childContextForFieldPath(path);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n const parsedValue = parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n }\n\n const mask = new FieldMask(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 */\nexport function parseQueryValue(\n userDataReader: UserDataReader,\n methodName: string,\n input: unknown,\n allowArrays = false\n): ProtoValue {\n const context = userDataReader.createContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName\n );\n const parsed = parseData(input, context);\n debugAssert(parsed != null, 'Parsed data should not be null.');\n debugAssert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\nexport function parseData(\n input: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n input = getModularInstance(input);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return parseObject(input, context);\n } else if (input instanceof FieldValue) {\n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n parseSentinelFieldValue(input, context);\n return null;\n } else if (input === undefined && context.ignoreUndefinedProperties) {\n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n } 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.settings.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return parseArray(input as unknown[], context);\n } else {\n return parseScalarValue(input, context);\n }\n }\n}\n\nfunction parseObject(\n obj: Dict<unknown>,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict<ProtoValue> = {};\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 = parseData(val, context.childContextForField(key));\n if (parsedValue != null) {\n fields[key] = parsedValue;\n }\n });\n }\n\n return { mapValue: { fields } };\n}\n\nfunction parseArray(array: unknown[], context: ParseContextImpl): ProtoValue {\n const values: ProtoValue[] = [];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = 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: 'NULL_VALUE' };\n }\n values.push(parsedEntry);\n entryIndex++;\n }\n return { arrayValue: { values } };\n}\n\n/**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\nfunction parseSentinelFieldValue(\n value: FieldValue,\n context: ParseContextImpl\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) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n const fieldTransform = value._toFieldTransform(context);\n if (fieldTransform) {\n context.fieldTransforms.push(fieldTransform);\n }\n}\n\n/**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */\nfunction parseScalarValue(\n value: unknown,\n context: ParseContextImpl\n): ProtoValue | null {\n value = getModularInstance(value);\n\n if (value === null) {\n return { nullValue: 'NULL_VALUE' };\n } else if (typeof value === 'number') {\n return toNumber(context.serializer, value);\n } else if (typeof value === 'boolean') {\n return { booleanValue: value };\n } else if (typeof value === 'string') {\n return { stringValue: value };\n } else if (value instanceof Date) {\n const timestamp = Timestamp.fromDate(value);\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\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 const timestamp = new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n );\n return {\n timestampValue: toTimestamp(context.serializer, timestamp)\n };\n } else if (value instanceof GeoPoint) {\n return {\n geoPointValue: {\n latitude: value.latitude,\n longitude: value.longitude\n }\n };\n } else if (value instanceof Bytes) {\n return { bytesValue: toBytes(context.serializer, value._byteString) };\n } else if (value instanceof DocumentReference) {\n const thisDb = context.databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw context.createError(\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 {\n referenceValue: toResourceName(\n value.firestore._databaseId || context.databaseId,\n value._key.path\n )\n };\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\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 Bytes) &&\n !(input instanceof DocumentReference) &&\n !(input instanceof FieldValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict<unknown> {\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 | PublicFieldPath | Compat<PublicFieldPath>,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n path = getModularInstance(path);\n\n if (path instanceof FieldPath) {\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 ';\n throw createError(\n message,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst FIELD_PATH_RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */\nexport function fieldPathFromDotSeparatedString(\n methodName: string,\n path: string,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n const found = path.search(FIELD_PATH_RESERVED);\n if (found >= 0) {\n throw createError(\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n\n try {\n return new FieldPath(...path.split('.'))._internalPath;\n } catch (e) {\n throw createError(\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`,\n methodName,\n /* hasConverter= */ false,\n /* path= */ undefined,\n targetDoc\n );\n }\n}\n\nfunction createError(\n reason: string,\n methodName: string,\n hasConverter: boolean,\n path?: InternalFieldPath,\n targetDoc?: DocumentKey\n): FirestoreError {\n const hasPath = path && !path.isEmpty();\n const hasDocument = targetDoc !== undefined;\n let message = `Function ${methodName}() called with invalid data`;\n if (hasConverter) {\n message += ' (via `toFirestore()`)';\n }\n message += '. ';\n\n let description = '';\n if (hasPath || hasDocument) {\n description += ' (found';\n\n if (hasPath) {\n description += ` in field ${path}`;\n }\n if (hasDocument) {\n description += ` in document ${targetDoc}`;\n }\n description += ')';\n }\n\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n message + reason + description\n );\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */\nfunction fieldMaskContains(\n haystack: InternalFieldPath[],\n needle: InternalFieldPath\n): boolean {\n return haystack.some(v => v.isEqual(needle));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { arrayEquals } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from './reference';\nimport {\n fieldPathFromDotSeparatedString,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue<number>) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise<void> {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter<Post, PostDbModel> {\n * toFirestore(post: WithFieldValue<Post>): WithFieldValue<PostDbModel> {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise<void> {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue<Post>` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue<Post>`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue<Post>\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot<Post> = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue<PostDbModel>` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue<PostDbModel>`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue<PostDbModel>\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot<Post> = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)}.\n *\n * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain Javascript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link @firebase/firestore/lite#(setDoc:1)},\n * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and\n * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true`\n * or `mergeFields`.\n *\n * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data()`.\n *\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and\n * metadata.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>\n ): AppModelType;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n\n /** @hideconstructor protected */\n constructor(\n public _firestore: Firestore,\n public _userDataWriter: AbstractUserDataWriter,\n public _key: DocumentKey,\n public _document: Document | null,\n public _converter: UntypedFirestoreDataConverter<\n AppModelType,\n DbModelType\n > | null\n ) {}\n\n /** Property of the `DocumentSnapshot` that provides the document's ID. */\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */\n get ref(): DocumentReference<AppModelType, DbModelType> {\n return new DocumentReference<AppModelType, DbModelType>(\n this._firestore,\n this._converter,\n this._key\n );\n }\n\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */\n exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n return this._document !== null;\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */\n data(): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(value);\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data(): AppModelType {\n return super.data() as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * The query on which you called {@link getDocs} in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query<AppModelType, DbModelType>;\n\n /** @hideconstructor */\n constructor(\n _query: Query<AppModelType, DbModelType>,\n readonly _docs: Array<QueryDocumentSnapshot<AppModelType, DbModelType>>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n return [...this._docs];\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this.docs.length;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.docs.length === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot<AppModelType, DbModelType>\n ) => void,\n thisArg?: unknown\n ): void {\n this._docs.forEach(callback, thisArg);\n }\n}\n\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>,\n right:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n left = getModularInstance(left);\n right = getModularInstance(right);\n\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n queryEqual(left.query, right.query) &&\n arrayEquals(left.docs, right.docs, snapshotEqual)\n );\n }\n\n return false;\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n arg: string | FieldPath | Compat<FieldPath>\n): InternalFieldPath {\n if (typeof arg === 'string') {\n return fieldPathFromDotSeparatedString(methodName, arg);\n } else if (arg instanceof FieldPath) {\n return arg._internalPath;\n } else {\n return arg._delegate._internalPath;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Bound } from '../core/bound';\nimport { DatabaseId } from '../core/database_info';\nimport {\n CompositeFilter,\n CompositeOperator,\n FieldFilter,\n Filter,\n Operator\n} from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport {\n isCollectionGroupQuery,\n LimitType,\n Query as InternalQuery,\n queryNormalizedOrderBy,\n queryWithAddedFilter,\n queryWithAddedOrderBy,\n queryWithEndAt,\n queryWithLimit,\n queryWithStartAt\n} from '../core/query';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldPath as InternalFieldPath, ResourcePath } from '../model/path';\nimport { isServerTimestamp } from '../model/server_timestamps';\nimport { refValue } from '../model/values';\nimport { Value as ProtoValue } from '../protos/firestore_proto_api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n validatePositiveNumber,\n valueDescription\n} from '../util/input_validation';\n\nimport { FieldPath } from './field_path';\nimport { DocumentData, DocumentReference, Query } from './reference';\nimport { DocumentSnapshot, fieldPathFromArgument } from './snapshot';\nimport {\n newUserDataReader,\n parseQueryValue,\n UserDataReader\n} from './user_data_reader';\n\nexport function validateHasExplicitOrderByForLimitToLast(\n query: InternalQuery\n): void {\n if (\n query.limitType === LimitType.Last &&\n query.explicitOrderBy.length === 0\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n}\n\n/** Describes the different query constraints available in this SDK. */\nexport type QueryConstraintType =\n | 'where'\n | 'orderBy'\n | 'limit'\n | 'limitToLast'\n | 'startAt'\n | 'startAfter'\n | 'endAt'\n | 'endBefore';\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */\nexport abstract class AppliableConstraint {\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link (query:1)} to create a new query instance that\n * also contains this `QueryConstraint`.\n */\nexport abstract class QueryConstraint extends AppliableConstraint {\n /** The type of this query constraint */\n abstract readonly type: QueryConstraintType;\n\n /**\n * Takes the provided {@link Query} and returns a copy of the {@link Query} with this\n * {@link AppliableConstraint} applied.\n */\n abstract _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType>;\n}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to\n * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or\n * {@link or}.\n * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to\n * apply (e.g. {@link orderBy}, {@link limit}).\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query<AppModelType, DbModelType>;\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also\n * include additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new\n * constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n ...queryConstraints: QueryConstraint[]\n): Query<AppModelType, DbModelType>;\n\nexport function query<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query<AppModelType, DbModelType> {\n let queryConstraints: AppliableConstraint[] = [];\n\n if (queryConstraint instanceof AppliableConstraint) {\n queryConstraints.push(queryConstraint);\n }\n\n queryConstraints = queryConstraints.concat(additionalQueryConstraints);\n\n validateQueryConstraintArray(queryConstraints);\n\n for (const constraint of queryConstraints) {\n query = constraint._apply(query);\n }\n return query;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link (query:1)} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */\nexport class QueryFieldFilterConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'where';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _op: Operator,\n private _value: unknown\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _op: Operator,\n _value: unknown\n ): QueryFieldFilterConstraint {\n return new QueryFieldFilterConstraint(_field, _op, _value);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const filter = this._parse(query);\n validateNewFieldFilter(query._query, filter);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, filter)\n );\n }\n\n _parse<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): FieldFilter {\n const reader = newUserDataReader(query.firestore);\n const filter = newQueryFilter(\n query._query,\n 'where',\n reader,\n query.firestore._databaseId,\n this._field,\n this._op,\n this._value\n );\n return filter;\n }\n}\n\n/**\n * Filter conditions in a {@link where} clause are specified using the\n * strings '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains', 'in',\n * 'array-contains-any', and 'not-in'.\n */\nexport type WhereFilterOp =\n | '<'\n | '<='\n | '=='\n | '!='\n | '>='\n | '>'\n | 'array-contains'\n | 'in'\n | 'array-contains-any'\n | 'not-in';\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"&lt;\", \"&lt;=\", \"==\", \"&lt;\",\n * \"&lt;=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */\nexport function where(\n fieldPath: string | FieldPath,\n opStr: WhereFilterOp,\n value: unknown\n): QueryFieldFilterConstraint {\n const op = opStr as Operator;\n const field = fieldPathFromArgument('where', fieldPath);\n return QueryFieldFilterConstraint._create(field, op, value);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n */\nexport class QueryCompositeFilterConstraint extends AppliableConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'or' | 'and',\n private readonly _queryConstraints: QueryFilterConstraint[]\n ) {\n super();\n }\n\n static _create(\n type: 'or' | 'and',\n _queryConstraints: QueryFilterConstraint[]\n ): QueryCompositeFilterConstraint {\n return new QueryCompositeFilterConstraint(type, _queryConstraints);\n }\n\n _parse<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Filter {\n const parsedFilters = this._queryConstraints\n .map(queryConstraint => {\n return queryConstraint._parse(query);\n })\n .filter(parsedFilter => parsedFilter.getFilters().length > 0);\n\n if (parsedFilters.length === 1) {\n return parsedFilters[0];\n }\n\n return CompositeFilter.create(parsedFilters, this._getOperator());\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const parsedFilter = this._parse(query);\n if (parsedFilter.getFilters().length === 0) {\n // Return the existing query if not adding any more filters (e.g. an empty\n // composite filter).\n return query;\n }\n validateNewFilter(query._query, parsedFilter);\n\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedFilter(query._query, parsedFilter)\n );\n }\n\n _getQueryConstraints(): readonly AppliableConstraint[] {\n return this._queryConstraints;\n }\n\n _getOperator(): CompositeOperator {\n return this.type === 'and' ? CompositeOperator.AND : CompositeOperator.OR;\n }\n}\n\n/**\n * `QueryNonFilterConstraint` is a helper union type that represents\n * QueryConstraints which are used to narrow or order the set of documents,\n * but that do not explicitly filter on a document field.\n * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},\n * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},\n * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}\n * to create a new query instance that also contains the `QueryConstraint`.\n */\nexport type QueryNonFilterConstraint =\n | QueryOrderByConstraint\n | QueryLimitConstraint\n | QueryStartAtConstraint\n | QueryEndAtConstraint;\n\n/**\n * `QueryFilterConstraint` is a helper union type that represents\n * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.\n */\nexport type QueryFilterConstraint =\n | QueryFieldFilterConstraint\n | QueryCompositeFilterConstraint;\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function or(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('or', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.OR,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n */\nexport function and(\n ...queryConstraints: QueryFilterConstraint[]\n): QueryCompositeFilterConstraint {\n // Only support QueryFilterConstraints\n queryConstraints.forEach(queryConstraint =>\n validateQueryFilterConstraint('and', queryConstraint)\n );\n\n return QueryCompositeFilterConstraint._create(\n CompositeOperator.AND,\n queryConstraints as QueryFilterConstraint[]\n );\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */\nexport class QueryOrderByConstraint extends QueryConstraint {\n /** The type of this query constraint */\n readonly type = 'orderBy';\n\n /**\n * @internal\n */\n protected constructor(\n private readonly _field: InternalFieldPath,\n private _direction: Direction\n ) {\n super();\n }\n\n static _create(\n _field: InternalFieldPath,\n _direction: Direction\n ): QueryOrderByConstraint {\n return new QueryOrderByConstraint(_field, _direction);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const orderBy = newQueryOrderBy(query._query, this._field, this._direction);\n return new Query(\n query.firestore,\n query.converter,\n queryWithAddedOrderBy(query._query, orderBy)\n );\n }\n}\n\n/**\n * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'\n * (descending or ascending).\n */\nexport type OrderByDirection = 'desc' | 'asc';\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */\nexport function orderBy(\n fieldPath: string | FieldPath,\n directionStr: OrderByDirection = 'asc'\n): QueryOrderByConstraint {\n const direction = directionStr as Direction;\n const path = fieldPathFromArgument('orderBy', fieldPath);\n return QueryOrderByConstraint._create(path, direction);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */\nexport class QueryLimitConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'limit' | 'limitToLast',\n private readonly _limit: number,\n private readonly _limitType: LimitType\n ) {\n super();\n }\n\n static _create(\n type: 'limit' | 'limitToLast',\n _limit: number,\n _limitType: LimitType\n ): QueryLimitConstraint {\n return new QueryLimitConstraint(type, _limit, _limitType);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n return new Query(\n query.firestore,\n query.converter,\n queryWithLimit(query._query, this._limit, this._limitType)\n );\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limit(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limit', limit);\n return QueryLimitConstraint._create('limit', limit, LimitType.First);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */\nexport function limitToLast(limit: number): QueryLimitConstraint {\n validatePositiveNumber('limitToLast', limit);\n return QueryLimitConstraint._create('limitToLast', limit, LimitType.Last);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */\nexport class QueryStartAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'startAt' | 'startAfter',\n private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query<AppModelType, DbModelType>(\n query.firestore,\n query.converter,\n queryWithStartAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided document (inclusive). The starting position is relative\n * to the order of the query. The document must contain all of the fields\n * provided in the `orderBy` of this query.\n *\n * @param snapshot - The snapshot of the document to start at.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start at the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query at, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`.\n */\nexport function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAt<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided document (exclusive). The starting position is\n * relative to the order of the query. The document must contain all of the\n * fields provided in the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to start after.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryStartAtConstraint;\n/**\n * Creates a {@link QueryStartAtConstraint} that modifies the result set to\n * start after the provided fields relative to the order of the query. The order\n * of the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to start this query after, in order\n * of the query's order by.\n * @returns A {@link QueryStartAtConstraint} to pass to `query()`\n */\nexport function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;\nexport function startAfter<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryStartAtConstraint {\n return QueryStartAtConstraint._create(\n 'startAfter',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */\nexport class QueryEndAtConstraint extends QueryConstraint {\n /**\n * @internal\n */\n protected constructor(\n /** The type of this query constraint */\n readonly type: 'endBefore' | 'endAt',\n private readonly _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array<unknown | DocumentSnapshot<unknown>>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n ): Query<AppModelType, DbModelType> {\n const bound = newQueryBoundFromDocOrFields(\n query,\n this.type,\n this._docOrFields,\n this._inclusive\n );\n return new Query(\n query.firestore,\n query.converter,\n queryWithEndAt(query._query, bound)\n );\n }\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided document (exclusive). The end position is relative to the\n * order of the query. The document must contain all of the fields provided in\n * the orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end before.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end\n * before the provided fields relative to the order of the query. The order of\n * the field values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query before, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endBefore<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endBefore',\n docOrFields,\n /*inclusive=*/ false\n );\n}\n\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided document (inclusive). The end position is relative to the order\n * of the query. The document must contain all of the fields provided in the\n * orderBy of the query.\n *\n * @param snapshot - The snapshot of the document to end at.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n snapshot: DocumentSnapshot<AppModelType, DbModelType>\n): QueryEndAtConstraint;\n/**\n * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at\n * the provided fields relative to the order of the query. The order of the field\n * values must match the order of the order by clauses of the query.\n *\n * @param fieldValues - The field values to end this query at, in order\n * of the query's order by.\n * @returns A {@link QueryEndAtConstraint} to pass to `query()`\n */\nexport function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;\nexport function endAt<AppModelType, DbModelType extends DocumentData>(\n ...docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>\n): QueryEndAtConstraint {\n return QueryEndAtConstraint._create(\n 'endAt',\n docOrFields,\n /*inclusive=*/ true\n );\n}\n\n/** Helper function to create a bound from a document or fields */\nfunction newQueryBoundFromDocOrFields<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>,\n methodName: string,\n docOrFields: Array<unknown | DocumentSnapshot<AppModelType, DbModelType>>,\n inclusive: boolean\n): Bound {\n docOrFields[0] = getModularInstance(docOrFields[0]);\n\n if (docOrFields[0] instanceof DocumentSnapshot) {\n return newQueryBoundFromDocument(\n query._query,\n query.firestore._databaseId,\n methodName,\n docOrFields[0]._document,\n inclusive\n );\n } else {\n const reader = newUserDataReader(query.firestore);\n return newQueryBoundFromFields(\n query._query,\n query.firestore._databaseId,\n reader,\n methodName,\n docOrFields,\n inclusive\n );\n }\n}\n\nexport function newQueryFilter(\n query: InternalQuery,\n methodName: string,\n dataReader: UserDataReader,\n databaseId: DatabaseId,\n fieldPath: InternalFieldPath,\n op: Operator,\n value: unknown\n): FieldFilter {\n let fieldValue: ProtoValue;\n if (fieldPath.isKeyField()) {\n if (op === Operator.ARRAY_CONTAINS || op === Operator.ARRAY_CONTAINS_ANY) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${op}' queries on documentId().`\n );\n } else if (op === Operator.IN || op === Operator.NOT_IN) {\n validateDisjunctiveFilterElements(value, op);\n const referenceList: ProtoValue[] = [];\n for (const arrayValue of value as ProtoValue[]) {\n referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));\n }\n fieldValue = { arrayValue: { values: referenceList } };\n } else {\n fieldValue = parseDocumentIdValue(databaseId, query, value);\n }\n } else {\n if (\n op === Operator.IN ||\n op === Operator.NOT_IN ||\n op === Operator.ARRAY_CONTAINS_ANY\n ) {\n validateDisjunctiveFilterElements(value, op);\n }\n fieldValue = parseQueryValue(\n dataReader,\n methodName,\n value,\n /* allowArrays= */ op === Operator.IN || op === Operator.NOT_IN\n );\n }\n const filter = FieldFilter.create(fieldPath, op, fieldValue);\n return filter;\n}\n\nexport function newQueryOrderBy(\n query: InternalQuery,\n fieldPath: InternalFieldPath,\n direction: Direction\n): OrderBy {\n if (query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call startAt() or startAfter() before ' +\n 'calling orderBy().'\n );\n }\n if (query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call endAt() or endBefore() before ' +\n 'calling orderBy().'\n );\n }\n const orderBy = new OrderBy(fieldPath, direction);\n return orderBy;\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 */\nexport function newQueryBoundFromDocument(\n query: InternalQuery,\n databaseId: DatabaseId,\n methodName: string,\n doc: Document | null,\n inclusive: boolean\n): Bound {\n if (!doc) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n\n const components: ProtoValue[] = [];\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 queryNormalizedOrderBy(query)) {\n if (orderBy.field.isKeyField()) {\n components.push(refValue(databaseId, doc.key));\n } else {\n const value = doc.data.field(orderBy.field);\n if (isServerTimestamp(value)) {\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, inclusive);\n}\n\n/**\n * Converts a list of field values to a `Bound` for the given query.\n */\nexport function newQueryBoundFromFields(\n query: InternalQuery,\n databaseId: DatabaseId,\n dataReader: UserDataReader,\n methodName: string,\n values: unknown[],\n inclusive: boolean\n): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = 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 orderBy() clauses`\n );\n }\n\n const components: ProtoValue[] = [];\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 (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = 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 `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(refValue(databaseId, key));\n } else {\n const wrapped = parseQueryValue(dataReader, methodName, rawValue);\n components.push(wrapped);\n }\n }\n\n return new Bound(components, inclusive);\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 */\nfunction parseDocumentIdValue(\n databaseId: DatabaseId,\n query: InternalQuery,\n documentIdValue: unknown\n): ProtoValue {\n documentIdValue = getModularInstance(documentIdValue);\n\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = query.path.child(ResourcePath.fromString(documentIdValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `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 refValue(databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n return refValue(databaseId, documentIdValue._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with 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 disjunctive filter satisfies all\n * array requirements.\n */\nfunction 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}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * This is not a comprehensive check, and this function should be removed in the\n * long term. Validations should occur in the Firestore backend.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one inequality per query.\n * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n */\nfunction conflictingOps(op: Operator): Operator[] {\n switch (op) {\n case Operator.NOT_EQUAL:\n return [Operator.NOT_EQUAL, Operator.NOT_IN];\n case Operator.ARRAY_CONTAINS_ANY:\n case Operator.IN:\n return [Operator.NOT_IN];\n case Operator.NOT_IN:\n return [\n Operator.ARRAY_CONTAINS_ANY,\n Operator.IN,\n Operator.NOT_IN,\n Operator.NOT_EQUAL\n ];\n default:\n return [];\n }\n}\n\nfunction validateNewFieldFilter(\n query: InternalQuery,\n fieldFilter: FieldFilter\n): void {\n const conflictingOp = findOpInsideFilters(\n query.filters,\n conflictingOps(fieldFilter.op)\n );\n if (conflictingOp !== null) {\n // Special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === fieldFilter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${fieldFilter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n}\n\nfunction validateNewFilter(query: InternalQuery, filter: Filter): void {\n let testQuery = query;\n const subFilters = filter.getFlattenedFilters();\n for (const subFilter of subFilters) {\n validateNewFieldFilter(testQuery, subFilter);\n testQuery = queryWithAddedFilter(testQuery, subFilter);\n }\n}\n\n// Checks if any of the provided filter operators are included in the given list of filters and\n// returns the first one that is, or null if none are.\nfunction findOpInsideFilters(\n filters: Filter[],\n operators: Operator[]\n): Operator | null {\n for (const filter of filters) {\n for (const fieldFilter of filter.getFlattenedFilters()) {\n if (operators.indexOf(fieldFilter.op) >= 0) {\n return fieldFilter.op;\n }\n }\n }\n return null;\n}\n\nexport function validateQueryFilterConstraint(\n functionName: string,\n queryConstraint: AppliableConstraint\n): void {\n if (\n !(queryConstraint instanceof QueryFieldFilterConstraint) &&\n !(queryConstraint instanceof QueryCompositeFilterConstraint)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`\n );\n }\n}\n\nfunction validateQueryConstraintArray(\n queryConstraint: AppliableConstraint[]\n): void {\n const compositeFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryCompositeFilterConstraint\n ).length;\n const fieldFilterCount = queryConstraint.filter(\n filter => filter instanceof QueryFieldFilterConstraint\n ).length;\n\n if (\n compositeFilterCount > 1 ||\n (compositeFilterCount > 0 && fieldFilterCount > 0)\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'InvalidQuery. When using composite filters, you cannot use ' +\n 'more than one filter at the top level. Consider nesting the multiple ' +\n 'filters within an `and(...)` statement. For example: ' +\n 'change `query(query, where(...), or(...))` to ' +\n '`query(query, and(where(...), or(...)))`.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentData } from '@firebase/firestore-types';\n\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport { ResourcePath } from '../model/path';\nimport {\n getLocalWriteTime,\n getPreviousValue\n} from '../model/server_timestamps';\nimport { TypeOrder } from '../model/type_order';\nimport { typeOrder } from '../model/values';\nimport {\n ApiClientObjectMap,\n ArrayValue as ProtoArrayValue,\n LatLng as ProtoLatLng,\n MapValue as ProtoMapValue,\n Timestamp as ProtoTimestamp,\n Value,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { isValidResourceName } from '../remote/serializer';\nimport { fail, hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { logError } from '../util/log';\nimport { forEach } from '../util/obj';\n\nimport { GeoPoint } from './geo_point';\nimport { Timestamp } from './timestamp';\n\nexport type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';\n\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */\nexport abstract class AbstractUserDataWriter {\n convertValue(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): unknown {\n switch (typeOrder(value)) {\n case TypeOrder.NullValue:\n return null;\n case TypeOrder.BooleanValue:\n return value.booleanValue!;\n case TypeOrder.NumberValue:\n return normalizeNumber(value.integerValue || value.doubleValue);\n case TypeOrder.TimestampValue:\n return this.convertTimestamp(value.timestampValue!);\n case TypeOrder.ServerTimestampValue:\n return this.convertServerTimestamp(value, serverTimestampBehavior);\n case TypeOrder.StringValue:\n return value.stringValue!;\n case TypeOrder.BlobValue:\n return this.convertBytes(normalizeByteString(value.bytesValue!));\n case TypeOrder.RefValue:\n return this.convertReference(value.referenceValue!);\n case TypeOrder.GeoPointValue:\n return this.convertGeoPoint(value.geoPointValue!);\n case TypeOrder.ArrayValue:\n return this.convertArray(value.arrayValue!, serverTimestampBehavior);\n case TypeOrder.ObjectValue:\n return this.convertObject(value.mapValue!, serverTimestampBehavior);\n default:\n throw fail('Invalid value type: ' + JSON.stringify(value));\n }\n }\n\n private convertObject(\n mapValue: ProtoMapValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): DocumentData {\n return this.convertObjectMap(mapValue.fields, serverTimestampBehavior);\n }\n\n /**\n * @internal\n */\n convertObjectMap(\n fields: ApiClientObjectMap<Value> | undefined,\n serverTimestampBehavior: ServerTimestampBehavior = 'none'\n ): DocumentData {\n const result: DocumentData = {};\n forEach(fields, (key, value) => {\n result[key] = this.convertValue(value, serverTimestampBehavior);\n });\n return result;\n }\n\n private convertGeoPoint(value: ProtoLatLng): GeoPoint {\n return new GeoPoint(\n normalizeNumber(value.latitude),\n normalizeNumber(value.longitude)\n );\n }\n\n private convertArray(\n arrayValue: ProtoArrayValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown[] {\n return (arrayValue.values || []).map(value =>\n this.convertValue(value, serverTimestampBehavior)\n );\n }\n\n private convertServerTimestamp(\n value: ProtoValue,\n serverTimestampBehavior: ServerTimestampBehavior\n ): unknown {\n switch (serverTimestampBehavior) {\n case 'previous':\n const previousValue = getPreviousValue(value);\n if (previousValue == null) {\n return null;\n }\n return this.convertValue(previousValue, serverTimestampBehavior);\n case 'estimate':\n return this.convertTimestamp(getLocalWriteTime(value));\n default:\n return null;\n }\n }\n\n private convertTimestamp(value: ProtoTimestamp): Timestamp {\n const normalizedValue = normalizeTimestamp(value);\n return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);\n }\n\n protected convertDocumentKey(\n name: string,\n expectedDatabaseId: DatabaseId\n ): DocumentKey {\n const resourcePath = ResourcePath.fromString(name);\n hardAssert(\n isValidResourceName(resourcePath),\n 'ReferenceValue is not valid ' + name\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\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 */\nexport function applyFirestoreDataConverter<T>(\n converter: UntypedFirestoreDataConverter<T> | null,\n value: WithFieldValue<T> | PartialWithFieldValue<T>,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue<T>);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(result.length === 1, 'Expected a single document result');\n const document = result[0];\n return new DocumentSnapshot<AppModelType, DbModelType>(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot<AppModelType, DbModelType>(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot<AppModelType, DbModelType>(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n reference = cast<CollectionReference<AppModelType, DbModelType>>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue<AppModelType>\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newQueryComparator } from '../core/query';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { FieldPath } from '../lite-api/field_path';\nimport {\n DocumentData,\n PartialWithFieldValue,\n Query,\n queryEqual,\n SetOptions,\n WithFieldValue\n} from '../lite-api/reference';\nimport {\n DocumentSnapshot as LiteDocumentSnapshot,\n fieldPathFromArgument,\n FirestoreDataConverter as LiteFirestoreDataConverter\n} from '../lite-api/snapshot';\nimport { UntypedFirestoreDataConverter } from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\n/**\n * Converter used by `withConverter()` to transform user objects of type\n * `AppModelType` into Firestore data of type `DbModelType`.\n *\n * Using the converter allows you to specify generic type arguments when\n * storing and retrieving objects from Firestore.\n *\n * In this context, an \"AppModel\" is a class that is used in an application to\n * package together related information and functionality. Such a class could,\n * for example, have properties with complex, nested data types, properties used\n * for memoization, properties of types not supported by Firestore (such as\n * `symbol` and `bigint`), and helper functions that perform compound\n * operations. Such classes are not suitable and/or possible to store into a\n * Firestore database. Instead, instances of such classes need to be converted\n * to \"plain old JavaScript objects\" (POJOs) with exclusively primitive\n * properties, potentially nested inside other POJOs or arrays of POJOs. In this\n * context, this type is referred to as the \"DbModel\" and would be an object\n * suitable for persisting into Firestore. For convenience, applications can\n * implement `FirestoreDataConverter` and register the converter with Firestore\n * objects, such as `DocumentReference` or `Query`, to automatically convert\n * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel`\n * to `AppModel` when retrieving from Firestore.\n *\n * @example\n *\n * Simple Example\n *\n * ```typescript\n * const numberConverter = {\n * toFirestore(value: WithFieldValue<number>) {\n * return { value };\n * },\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {\n * return snapshot.data(options).value as number;\n * }\n * };\n *\n * async function simpleDemo(db: Firestore): Promise<void> {\n * const documentRef = doc(db, 'values/value123').withConverter(numberConverter);\n *\n * // converters are used with `setDoc`, `addDoc`, and `getDoc`\n * await setDoc(documentRef, 42);\n * const snapshot1 = await getDoc(documentRef);\n * assertEqual(snapshot1.data(), 42);\n *\n * // converters are not used when writing data with `updateDoc`\n * await updateDoc(documentRef, { value: 999 });\n * const snapshot2 = await getDoc(documentRef);\n * assertEqual(snapshot2.data(), 999);\n * }\n * ```\n *\n * Advanced Example\n *\n * ```typescript\n * // The Post class is a model that is used by our application.\n * // This class may have properties and methods that are specific\n * // to our application execution, which do not need to be persisted\n * // to Firestore.\n * class Post {\n * constructor(\n * readonly title: string,\n * readonly author: string,\n * readonly lastUpdatedMillis: number\n * ) {}\n * toString(): string {\n * return `${this.title} by ${this.author}`;\n * }\n * }\n *\n * // The PostDbModel represents how we want our posts to be stored\n * // in Firestore. This DbModel has different properties (`ttl`,\n * // `aut`, and `lut`) from the Post class we use in our application.\n * interface PostDbModel {\n * ttl: string;\n * aut: { firstName: string; lastName: string };\n * lut: Timestamp;\n * }\n *\n * // The `PostConverter` implements `FirestoreDataConverter` and specifies\n * // how the Firestore SDK can convert `Post` objects to `PostDbModel`\n * // objects and vice versa.\n * class PostConverter implements FirestoreDataConverter<Post, PostDbModel> {\n * toFirestore(post: WithFieldValue<Post>): WithFieldValue<PostDbModel> {\n * return {\n * ttl: post.title,\n * aut: this._autFromAuthor(post.author),\n * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)\n * };\n * }\n *\n * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {\n * const data = snapshot.data(options) as PostDbModel;\n * const author = `${data.aut.firstName} ${data.aut.lastName}`;\n * return new Post(data.ttl, author, data.lut.toMillis());\n * }\n *\n * _autFromAuthor(\n * author: string | FieldValue\n * ): { firstName: string; lastName: string } | FieldValue {\n * if (typeof author !== 'string') {\n * // `author` is a FieldValue, so just return it.\n * return author;\n * }\n * const [firstName, lastName] = author.split(' ');\n * return {firstName, lastName};\n * }\n *\n * _lutFromLastUpdatedMillis(\n * lastUpdatedMillis: number | FieldValue\n * ): Timestamp | FieldValue {\n * if (typeof lastUpdatedMillis !== 'number') {\n * // `lastUpdatedMillis` must be a FieldValue, so just return it.\n * return lastUpdatedMillis;\n * }\n * return Timestamp.fromMillis(lastUpdatedMillis);\n * }\n * }\n *\n * async function advancedDemo(db: Firestore): Promise<void> {\n * // Create a `DocumentReference` with a `FirestoreDataConverter`.\n * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());\n *\n * // The `data` argument specified to `setDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `Post`. Since the `data`\n * // argument is typed as `WithFieldValue<Post>` rather than just `Post`,\n * // this allows properties of the `data` argument to also be special\n * // Firestore values that perform server-side mutations, such as\n * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.\n * await setDoc(documentRef, {\n * title: 'My Life',\n * author: 'Foo Bar',\n * lastUpdatedMillis: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `setDoc()` is _not_ compatible with `WithFieldValue<Post>`. This\n * // type checking prevents the caller from specifying objects with incorrect\n * // properties or property values.\n * // @ts-expect-error \"Argument of type { ttl: string; } is not assignable\n * // to parameter of type WithFieldValue<Post>\"\n * await setDoc(documentRef, { ttl: 'The Title' });\n *\n * // When retrieving a document with `getDoc()` the `DocumentSnapshot`\n * // object's `data()` method returns a `Post`, rather than a generic object,\n * // which would have been returned if the `DocumentReference` did _not_ have a\n * // `FirestoreDataConverter` attached to it.\n * const snapshot1: DocumentSnapshot<Post> = await getDoc(documentRef);\n * const post1: Post = snapshot1.data()!;\n * if (post1) {\n * assertEqual(post1.title, 'My Life');\n * assertEqual(post1.author, 'Foo Bar');\n * }\n *\n * // The `data` argument specified to `updateDoc()` is type checked by the\n * // TypeScript compiler to be compatible with `PostDbModel`. Note that\n * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`,\n * // the `data` argument to `updateDoc()` must be compatible with\n * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed\n * // as `WithFieldValue<PostDbModel>` rather than just `PostDbModel`, this\n * // allows properties of the `data` argument to also be those special\n * // Firestore values, like `arrayRemove()`, `deleteField()`, and\n * // `serverTimestamp()`.\n * await updateDoc(documentRef, {\n * 'aut.firstName': 'NewFirstName',\n * lut: serverTimestamp()\n * });\n *\n * // The TypeScript compiler will fail to compile if the `data` argument to\n * // `updateDoc()` is _not_ compatible with `WithFieldValue<PostDbModel>`.\n * // This type checking prevents the caller from specifying objects with\n * // incorrect properties or property values.\n * // @ts-expect-error \"Argument of type { title: string; } is not assignable\n * // to parameter of type WithFieldValue<PostDbModel>\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot<Post> = await getDoc(documentRef);\n * const post2: Post = snapshot2.data()!;\n * if (post2) {\n * assertEqual(post2.title, 'My Life');\n * assertEqual(post2.author, 'NewFirstName Bar');\n * }\n * }\n * ```\n */\nexport interface FirestoreDataConverter<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n> extends LiteFirestoreDataConverter<AppModelType, DbModelType> {\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. To use `set()`\n * with `merge` and `mergeFields`, `toFirestore()` must be defined with\n * `PartialWithFieldValue<AppModelType>`.\n *\n * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as\n * {@link (deleteField:1)} to be used as property values.\n */\n toFirestore(\n modelObject: WithFieldValue<AppModelType>\n ): WithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert a custom model object of type\n * `AppModelType` into a plain JavaScript object (suitable for writing\n * directly to the Firestore database) of type `DbModelType`. Used with\n * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and\n * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.\n *\n * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow\n * FieldValues such as {@link (arrayUnion:1)} to be used as property values.\n * It also supports nested `Partial` by allowing nested fields to be\n * omitted.\n */\n toFirestore(\n modelObject: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): PartialWithFieldValue<DbModelType>;\n\n /**\n * Called by the Firestore SDK to convert Firestore data into an object of\n * type `AppModelType`. You can access your data by calling:\n * `snapshot.data(options)`.\n *\n * Generally, the data returned from `snapshot.data()` can be cast to\n * `DbModelType`; however, this is not guaranteed because Firestore does not\n * enforce a schema on the database. For example, writes from a previous\n * version of the application or writes from another client that did not use a\n * type converter could have written data with different properties and/or\n * property types. The implementation will need to choose whether to\n * gracefully recover from non-conforming data or throw an error.\n *\n * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}.\n *\n * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.\n * @param options - The `SnapshotOptions` from the initial call to `data()`.\n */\n fromFirestore(\n snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>,\n options?: SnapshotOptions\n ): AppModelType;\n}\n\n/**\n * Options that configure how data is retrieved from a `DocumentSnapshot` (for\n * example the desired behavior for server timestamps that have not yet been set\n * to their final value).\n */\nexport interface SnapshotOptions {\n /**\n * If set, controls the return value for server timestamps that have not yet\n * been set to their final value.\n *\n * By specifying 'estimate', pending server timestamps return an estimate\n * based on the local clock. This estimate will differ from the final value\n * and cause these values to change once the server result becomes available.\n *\n * By specifying 'previous', pending timestamps will be ignored and return\n * their previous value instead.\n *\n * If omitted or set to 'none', `null` will be returned by default until the\n * server value becomes available.\n */\n readonly serverTimestamps?: 'estimate' | 'previous' | 'none';\n}\n\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */\nexport class SnapshotMetadata {\n /**\n * True if the snapshot contains the result of local writes (for example\n * `set()` or `update()` calls) that have not yet been committed to the\n * backend. If your listener has opted into metadata updates (via\n * `SnapshotListenOptions`) you will receive another snapshot with\n * `hasPendingWrites` equal to false once the writes have been committed to\n * the backend.\n */\n readonly hasPendingWrites: boolean;\n\n /**\n * True if the snapshot was created from cached data rather than guaranteed\n * up-to-date server data. If your listener has opted into metadata updates\n * (via `SnapshotListenOptions`) you will receive another snapshot with\n * `fromCache` set to false once the client has received up-to-date data from\n * the backend.\n */\n readonly fromCache: boolean;\n\n /** @hideconstructor */\n constructor(hasPendingWrites: boolean, fromCache: boolean) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */\n isEqual(other: SnapshotMetadata): boolean {\n return (\n this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache\n );\n }\n}\n\n/**\n * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.\n */\nexport type DocumentChangeType = 'added' | 'removed' | 'modified';\n\n/**\n * A `DocumentChange` represents a change to the documents matching a query.\n * It contains the document affected and the type of change that occurred.\n */\nexport interface DocumentChange<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** The type of change ('added', 'modified', or 'removed'). */\n readonly type: DocumentChangeType;\n\n /** The document affected by this change. */\n readonly doc: QueryDocumentSnapshot<AppModelType, DbModelType>;\n\n /**\n * The index of the changed document in the result set immediately prior to\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects\n * have been applied). Is `-1` for 'added' events.\n */\n readonly oldIndex: number;\n\n /**\n * The index of the changed document in the result set immediately after\n * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`\n * objects and the current `DocumentChange` object have been applied).\n * Is -1 for 'removed' events.\n */\n readonly newIndex: number;\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */\nexport class DocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends LiteDocumentSnapshot<AppModelType, DbModelType> {\n private readonly _firestoreImpl: Firestore;\n\n /**\n * Metadata about the `DocumentSnapshot`, including information about its\n * source and local modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /** @hideconstructor protected */\n constructor(\n readonly _firestore: Firestore,\n userDataWriter: AbstractUserDataWriter,\n key: DocumentKey,\n document: Document | null,\n metadata: SnapshotMetadata,\n converter: UntypedFirestoreDataConverter<AppModelType, DbModelType> | null\n ) {\n super(_firestore, userDataWriter, key, document, converter);\n this._firestoreImpl = _firestore;\n this.metadata = metadata;\n }\n\n /**\n * Returns whether or not the data exists. True if the document exists.\n */\n exists(): this is QueryDocumentSnapshot<AppModelType, DbModelType> {\n return super.exists();\n }\n\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */\n data(options: SnapshotOptions = {}): AppModelType | undefined {\n if (!this._document) {\n return undefined;\n } else if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._userDataWriter,\n this._key,\n this._document,\n this.metadata,\n /* converter= */ null\n );\n return this._converter.fromFirestore(snapshot, options);\n } else {\n return this._userDataWriter.convertValue(\n this._document.data.value,\n options.serverTimestamps\n ) as AppModelType;\n }\n }\n\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(fieldPath: string | FieldPath, options: SnapshotOptions = {}): any {\n if (this._document) {\n const value = this._document.data.field(\n fieldPathFromArgument('DocumentSnapshot.get', fieldPath)\n );\n if (value !== null) {\n return this._userDataWriter.convertValue(\n value,\n options.serverTimestamps\n );\n }\n }\n return undefined;\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */\nexport class QueryDocumentSnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> extends DocumentSnapshot<AppModelType, DbModelType> {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(options: SnapshotOptions = {}): AppModelType {\n return super.data(options) as AppModelType;\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */\nexport class QuerySnapshot<\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /**\n * Metadata about this snapshot, concerning its source and if it has local\n * modifications.\n */\n readonly metadata: SnapshotMetadata;\n\n /**\n * The query on which you called `get` or `onSnapshot` in order to get this\n * `QuerySnapshot`.\n */\n readonly query: Query<AppModelType, DbModelType>;\n\n private _cachedChanges?: Array<DocumentChange<AppModelType, DbModelType>>;\n private _cachedChangesIncludeMetadataChanges?: boolean;\n\n /** @hideconstructor */\n constructor(\n readonly _firestore: Firestore,\n readonly _userDataWriter: AbstractUserDataWriter,\n query: Query<AppModelType, DbModelType>,\n readonly _snapshot: ViewSnapshot\n ) {\n this.metadata = new SnapshotMetadata(\n _snapshot.hasPendingWrites,\n _snapshot.fromCache\n );\n this.query = query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array<QueryDocumentSnapshot<AppModelType, DbModelType>> {\n const result: Array<QueryDocumentSnapshot<AppModelType, DbModelType>> = [];\n this.forEach(doc => result.push(doc));\n return result;\n }\n\n /** The number of documents in the `QuerySnapshot`. */\n get size(): number {\n return this._snapshot.docs.size;\n }\n\n /** True if there are no documents in the `QuerySnapshot`. */\n get empty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */\n forEach(\n callback: (\n result: QueryDocumentSnapshot<AppModelType, DbModelType>\n ) => void,\n thisArg?: unknown\n ): void {\n this._snapshot.docs.forEach(doc => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot<AppModelType, DbModelType>(\n this._firestore,\n this._userDataWriter,\n doc.key,\n doc,\n new SnapshotMetadata(\n this._snapshot.mutatedKeys.has(doc.key),\n this._snapshot.fromCache\n ),\n this.query.converter\n )\n );\n });\n }\n\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */\n docChanges(\n options: SnapshotListenOptions = {}\n ): Array<DocumentChange<AppModelType, DbModelType>> {\n const includeMetadataChanges = !!options.includeMetadataChanges;\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(this, includeMetadataChanges);\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n }\n\n return this._cachedChanges;\n }\n}\n\n/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\nexport function changesFromSnapshot<\n AppModelType,\n DbModelType extends DocumentData\n>(\n querySnapshot: QuerySnapshot<AppModelType, DbModelType>,\n includeMetadataChanges: boolean\n): Array<DocumentChange<AppModelType, DbModelType>> {\n if (querySnapshot._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 querySnapshot._snapshot.docChanges.map(change => {\n debugAssert(\n change.type === ChangeType.Added,\n 'Invalid event type for first snapshot'\n );\n debugAssert(\n !lastDoc ||\n newQueryComparator(querySnapshot._snapshot.query)(\n lastDoc,\n change.doc\n ) < 0,\n 'Got added events in wrong order'\n );\n const doc = new QueryDocumentSnapshot<AppModelType, DbModelType>(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n lastDoc = change.doc;\n return {\n type: 'added' as 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 = querySnapshot._snapshot.oldDocs;\n return querySnapshot._snapshot.docChanges\n .filter(\n change => includeMetadataChanges || change.type !== ChangeType.Metadata\n )\n .map(change => {\n const doc = new QueryDocumentSnapshot<AppModelType, DbModelType>(\n querySnapshot._firestore,\n querySnapshot._userDataWriter,\n change.doc.key,\n change.doc,\n new SnapshotMetadata(\n querySnapshot._snapshot.mutatedKeys.has(change.doc.key),\n querySnapshot._snapshot.fromCache\n ),\n querySnapshot.query.converter\n );\n let oldIndex = -1;\n let newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker.indexOf(change.doc.key);\n debugAssert(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 {\n type: resultChangeType(change.type),\n doc,\n oldIndex,\n newIndex\n };\n });\n }\n}\n\nexport function resultChangeType(type: ChangeType): 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// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */\nexport function snapshotEqual<AppModelType, DbModelType extends DocumentData>(\n left:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>,\n right:\n | DocumentSnapshot<AppModelType, DbModelType>\n | QuerySnapshot<AppModelType, DbModelType>\n): boolean {\n if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {\n return (\n left._firestore === right._firestore &&\n left._key.isEqual(right._key) &&\n (left._document === null\n ? right._document === null\n : left._document.isEqual(right._document)) &&\n left._converter === right._converter\n );\n } else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {\n return (\n left._firestore === right._firestore &&\n queryEqual(left.query, right.query) &&\n left.metadata.isEqual(right.metadata) &&\n left._snapshot.isEqual(right._snapshot)\n );\n }\n\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver\n} from '../api/observer';\nimport {\n firestoreClientAddSnapshotsInSyncListener,\n firestoreClientGetDocumentFromLocalCache,\n firestoreClientGetDocumentsFromLocalCache,\n firestoreClientGetDocumentsViaSnapshotListener,\n firestoreClientGetDocumentViaSnapshotListener,\n firestoreClientListen,\n firestoreClientWrite\n} from '../core/firestore_client';\nimport { newQueryForPath, Query as InternalQuery } from '../core/query';\nimport { ViewSnapshot } from '../core/view_snapshot';\nimport { Bytes } from '../lite-api/bytes';\nimport { FieldPath } from '../lite-api/field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from '../lite-api/query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from '../lite-api/reference';\nimport { applyFirestoreDataConverter } from '../lite-api/reference_impl';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs\n} from '../lite-api/user_data_reader';\nimport { AbstractUserDataWriter } from '../lite-api/user_data_writer';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { DocumentSnapshot, QuerySnapshot, SnapshotMetadata } from './snapshot';\n\n/**\n * An options object that can be passed to {@link (onSnapshot:1)} and {@link\n * QuerySnapshot.docChanges} to control which types of changes to include in the\n * result set.\n */\nexport interface SnapshotListenOptions {\n /**\n * Include a change even if only the metadata of the query or of a document\n * changed. Default is false.\n */\n readonly includeMetadataChanges?: boolean;\n}\n\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(\n client,\n reference._key\n ).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\nexport class ExpUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromCache<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(\n doc =>\n new DocumentSnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n reference._key,\n doc,\n new SnapshotMetadata(\n doc !== null && doc.hasLocalMutations,\n /* fromCache= */ true\n ),\n reference.converter\n )\n );\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nexport function getDocFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, {\n source: 'server'\n }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocs<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n validateHasExplicitOrderByForLimitToLast(query._query);\n return firestoreClientGetDocumentsViaSnapshotListener(\n client,\n query._query\n ).then(\n snapshot =>\n new QuerySnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromCache<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsFromLocalCache(client, query._query).then(\n snapshot =>\n new QuerySnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n query,\n snapshot\n )\n );\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */\nexport function getDocsFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query<AppModelType, DbModelType>\n): Promise<QuerySnapshot<AppModelType, DbModelType>> {\n query = cast<Query<AppModelType, DbModelType>>(query, Query);\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, {\n source: 'server'\n }).then(\n snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n}\n\n/**\n * Writes to the document referred to by this `DocumentReference`. If the\n * document does not yet exist, it will be created.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<void>;\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created. If you provide `merge`\n * or `mergeFields`, the provided data can be merged into an existing document.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @returns A Promise resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n): Promise<void>;\nexport function setDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as WithFieldValue<AppModelType>,\n options\n );\n const dataReader = newUserDataReader(firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const mutation = parsed.toMutation(reference._key, Precondition.none());\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n): Promise<void>;\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference` The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend (note that it won't resolve while you're offline).\n */\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void>;\nexport function updateDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<unknown>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise<void> {\n reference = cast<DocumentReference<AppModelType, DbModelType>>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const dataReader = newUserDataReader(firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const mutation = parsed.toMutation(reference._key, Precondition.exists(true));\n return executeWrite(firestore, [mutation]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */\nexport function deleteDoc<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>\n): Promise<void> {\n const firestore = cast(reference.firestore, Firestore);\n const mutations = [new DeleteMutation(reference._key, Precondition.none())];\n return executeWrite(firestore, mutations);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */\nexport function addDoc<AppModelType, DbModelType extends DocumentData>(\n reference: CollectionReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n): Promise<DocumentReference<AppModelType, DbModelType>> {\n const firestore = cast(reference.firestore, Firestore);\n\n const docRef = doc(reference);\n const convertedValue = applyFirestoreDataConverter(reference.converter, data);\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n reference.converter !== null,\n {}\n );\n\n const mutation = parsed.toMutation(docRef._key, Precondition.exists(false));\n return executeWrite(firestore, [mutation]).then(() => docRef);\n}\n\n/**\n * A function returned by `onSnapshot()` that removes the listener when invoked.\n */\nexport interface Unsubscribe {\n /** Removes the listener when invoked. */\n (): void;\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n observer: {\n next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param reference - A reference to the document to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot`\n * is available.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference: DocumentReference<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n observer: {\n next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events. You may either pass\n * individual `onNext` and `onError` callbacks or pass a single observer\n * object with `next` and `error` callbacks. The listener can be cancelled by\n * calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will\n * never be called because the snapshot stream is never-ending.\n *\n * @param query - The query to listen to.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot`\n * is available.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param onError - A callback to be called if the listen fails or is\n * cancelled. No further callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n query: Query<AppModelType, DbModelType>,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\nexport function onSnapshot<AppModelType, DbModelType extends DocumentData>(\n reference:\n | Query<AppModelType, DbModelType>\n | DocumentReference<AppModelType, DbModelType>,\n ...args: unknown[]\n): Unsubscribe {\n reference = getModularInstance(reference);\n\n let options: SnapshotListenOptions = {\n includeMetadataChanges: false\n };\n let currArg = 0;\n if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) {\n options = args[currArg] as SnapshotListenOptions;\n currArg++;\n }\n\n const internalOptions = {\n includeMetadataChanges: options.includeMetadataChanges\n };\n\n if (isPartialObserver(args[currArg])) {\n const userObserver = args[currArg] as PartialObserver<\n QuerySnapshot<AppModelType, DbModelType>\n >;\n args[currArg] = userObserver.next?.bind(userObserver);\n args[currArg + 1] = userObserver.error?.bind(userObserver);\n args[currArg + 2] = userObserver.complete?.bind(userObserver);\n }\n\n let observer: PartialObserver<ViewSnapshot>;\n let firestore: Firestore;\n let internalQuery: InternalQuery;\n\n if (reference instanceof DocumentReference) {\n firestore = cast(reference.firestore, Firestore);\n internalQuery = newQueryForPath(reference._key.path);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (\n args[currArg] as NextFn<DocumentSnapshot<AppModelType, DbModelType>>\n )(\n convertToDocSnapshot(\n firestore,\n reference as DocumentReference<AppModelType, DbModelType>,\n snapshot\n )\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n } else {\n const query = cast<Query<AppModelType, DbModelType>>(reference, Query);\n firestore = cast(query.firestore, Firestore);\n internalQuery = query._query;\n const userDataWriter = new ExpUserDataWriter(firestore);\n\n observer = {\n next: snapshot => {\n if (args[currArg]) {\n (args[currArg] as NextFn<QuerySnapshot<AppModelType, DbModelType>>)(\n new QuerySnapshot(firestore, userDataWriter, query, snapshot)\n );\n }\n },\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n\n validateHasExplicitOrderByForLimitToLast(reference._query);\n }\n\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientListen(\n client,\n internalQuery,\n internalOptions,\n observer\n );\n}\n\n// TODO(firestorexp): Make sure these overloads are tested via the Firestore\n// integration tests\n\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use SnapshotMetadata in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The instance of Firestore for synchronizing snapshots.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n observer: {\n next?: (value: void) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n }\n): Unsubscribe;\n/**\n * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync\n * event indicates that all listeners affected by a given change have fired,\n * even if a single server-generated change affects multiple listeners.\n *\n * NOTE: The snapshots-in-sync event only indicates that listeners are in sync\n * with each other, but does not relate to whether those snapshots are in sync\n * with the server. Use `SnapshotMetadata` in the individual listeners to\n * determine if a snapshot is from the cache or the server.\n *\n * @param firestore - The `Firestore` instance for synchronizing snapshots.\n * @param onSync - A callback to be called every time all snapshot listeners are\n * in sync with each other.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n */\nexport function onSnapshotsInSync(\n firestore: Firestore,\n onSync: () => void\n): Unsubscribe;\nexport function onSnapshotsInSync(\n firestore: Firestore,\n arg: unknown\n): Unsubscribe {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const observer = isPartialObserver(arg)\n ? (arg as PartialObserver<void>)\n : {\n next: arg as () => void\n };\n\n return firestoreClientAddSnapshotsInSyncListener(client, observer);\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */\nexport function executeWrite(\n firestore: Firestore,\n mutations: Mutation[]\n): Promise<void> {\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientWrite(client, mutations);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */\nfunction convertToDocSnapshot<AppModelType, DbModelType extends DocumentData>(\n firestore: Firestore,\n ref: DocumentReference<AppModelType, DbModelType>,\n snapshot: ViewSnapshot\n): DocumentSnapshot<AppModelType, DbModelType> {\n debugAssert(\n snapshot.docs.size <= 1,\n 'Expected zero or a single result on a document-only query'\n );\n const doc = snapshot.docs.get(ref._key);\n\n const userDataWriter = new ExpUserDataWriter(firestore);\n return new DocumentSnapshot<AppModelType, DbModelType>(\n firestore,\n userDataWriter,\n ref._key,\n doc,\n new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache),\n ref.converter\n );\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise<void>\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): WriteBatch;\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType> | PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise<void> {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\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\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference<AppModelType, DbModelType>\n | Compat<DocumentReference<AppModelType, DbModelType>>,\n firestore: Firestore\n): DocumentReference<AppModelType, DbModelType> {\n documentRef = getModularInstance(documentRef);\n\n 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 as DocumentReference<AppModelType, DbModelType>;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n TransactionOptions as TranasactionOptionsInternal,\n DEFAULT_TRANSACTION_OPTIONS,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n _transaction: InternalTransaction\n ) {\n super(_firestore, _transaction);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>\n ): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new ExpUserDataWriter(this._firestore);\n return super\n .get(documentRef)\n .then(\n liteDocumentSnapshot =>\n new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n liteDocumentSnapshot._document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n ref.converter\n )\n );\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction<T>(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise<T>,\n options?: TransactionOptions\n): Promise<T> {\n firestore = cast(firestore, Firestore);\n const optionsWithDefaults: TranasactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientTransaction(\n client,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n optionsWithDefaults\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TranasactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>\n ): Promise<DocumentSnapshot<AppModelType, DbModelType>> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\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.isFoundDocument()) {\n return new DocumentSnapshot<AppModelType, DbModelType>(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot<AppModelType, DbModelType>(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n `BatchGetDocumentsRequest returned unexpected document: ${doc}`\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: WithFieldValue<AppModelType>\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: PartialWithFieldValue<AppModelType>,\n options: SetOptions\n ): this;\n set<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n value: PartialWithFieldValue<AppModelType>,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n data: UpdateData<DbModelType>\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>,\n fieldOrUpdateData: string | FieldPath | UpdateData<DbModelType>,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete<AppModelType, DbModelType extends DocumentData>(\n documentRef: DocumentReference<AppModelType, DbModelType>\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction<T>(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise<T>,\n options?: TransactionOptions\n): Promise<T> {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TranasactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred<T>();\n new TransactionRunner<T>(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '@firebase/firestore';\nimport { SetOptions } from '@firebase/firestore-types';\n\nexport function validateSetOptions(\n methodName: string,\n options: SetOptions | undefined\n): SetOptions {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n\n if (options.mergeFields !== undefined && options.merge !== undefined) {\n throw new FirestoreError(\n 'invalid-argument',\n `Invalid options passed to function ${methodName}(): You cannot ` +\n 'specify both \"merge\" and \"mergeFields\".'\n );\n }\n\n return options;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Bytes, FirestoreError, _isBase64Available } from '@firebase/firestore';\nimport { Compat } from '@firebase/util';\n\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable(): void {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(\n '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 (!_isBase64Available()) {\n throw new FirestoreError(\n 'unimplemented',\n 'Blobs are unavailable in Firestore in this environment.'\n );\n }\n}\n\n/** Immutable class holding a blob (binary data) */\nexport class Blob implements Compat<Bytes> {\n constructor(readonly _delegate: Bytes) {}\n static fromBase64String(base64: string): Blob {\n assertBase64Available();\n return new Blob(Bytes.fromBase64String(base64));\n }\n\n static fromUint8Array(array: Uint8Array): Blob {\n assertUint8ArrayAvailable();\n return new Blob(Bytes.fromUint8Array(array));\n }\n\n toBase64(): string {\n assertBase64Available();\n return this._delegate.toBase64();\n }\n\n toUint8Array(): Uint8Array {\n assertUint8ArrayAvailable();\n return this._delegate.toUint8Array();\n }\n\n isEqual(other: Blob): boolean {\n return this._delegate.isEqual(other._delegate);\n }\n\n toString(): string {\n return 'Blob(base64: ' + this.toBase64() + ')';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '@firebase/firestore';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => 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 function isPartialObserver<T>(obj: unknown): obj is PartialObserver<T> {\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 Record<string, 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { _FirebaseApp, FirebaseService } from '@firebase/app-types/private';\nimport {\n LoadBundleTask,\n Bytes,\n clearIndexedDbPersistence,\n disableNetwork,\n enableIndexedDbPersistence,\n enableMultiTabIndexedDbPersistence,\n enableNetwork,\n ensureFirestoreConfigured,\n Firestore as ExpFirestore,\n connectFirestoreEmulator,\n waitForPendingWrites,\n FieldPath as ExpFieldPath,\n limit,\n limitToLast,\n where,\n orderBy,\n startAfter,\n startAt,\n query,\n endBefore,\n endAt,\n doc,\n collection,\n collectionGroup,\n queryEqual,\n Query as ExpQuery,\n CollectionReference as ExpCollectionReference,\n DocumentReference as ExpDocumentReference,\n refEqual,\n addDoc,\n deleteDoc,\n executeWrite,\n getDoc,\n getDocFromCache,\n getDocFromServer,\n getDocs,\n getDocsFromCache,\n getDocsFromServer,\n onSnapshot,\n onSnapshotsInSync,\n setDoc,\n updateDoc,\n Unsubscribe,\n DocumentChange as ExpDocumentChange,\n DocumentSnapshot as ExpDocumentSnapshot,\n QueryDocumentSnapshot as ExpQueryDocumentSnapshot,\n QuerySnapshot as ExpQuerySnapshot,\n snapshotEqual,\n SnapshotMetadata,\n runTransaction,\n Transaction as ExpTransaction,\n WriteBatch as ExpWriteBatch,\n AbstractUserDataWriter,\n FirestoreError,\n FirestoreDataConverter as ModularFirestoreDataConverter,\n setLogLevel as setClientLogLevel,\n _DatabaseId,\n _validateIsNotUsedTogether,\n _cast,\n _DocumentKey,\n _debugAssert,\n _FieldPath,\n _ResourcePath,\n _ByteString,\n _logWarn,\n namedQuery,\n loadBundle,\n PartialWithFieldValue,\n WithFieldValue\n} from '@firebase/firestore';\nimport {\n CollectionReference as PublicCollectionReference,\n DocumentChange as PublicDocumentChange,\n DocumentChangeType as PublicDocumentChangeType,\n DocumentData,\n DocumentData as PublicDocumentData,\n DocumentReference as PublicDocumentReference,\n DocumentSnapshot as PublicDocumentSnapshot,\n FieldPath as PublicFieldPath,\n FirebaseFirestore as PublicFirestore,\n FirestoreDataConverter as PublicFirestoreDataConverter,\n GetOptions as PublicGetOptions,\n LogLevel as PublicLogLevel,\n OrderByDirection as PublicOrderByDirection,\n PersistenceSettings as PublicPersistenceSettings,\n Query as PublicQuery,\n QueryDocumentSnapshot as PublicQueryDocumentSnapshot,\n QuerySnapshot as PublicQuerySnapshot,\n SetOptions as PublicSetOptions,\n Settings as PublicSettings,\n SnapshotListenOptions as PublicSnapshotListenOptions,\n SnapshotOptions as PublicSnapshotOptions,\n Transaction as PublicTransaction,\n UpdateData as PublicUpdateData,\n WhereFilterOp as PublicWhereFilterOp,\n WriteBatch as PublicWriteBatch\n} from '@firebase/firestore-types';\nimport {\n Compat,\n EmulatorMockTokenOptions,\n getModularInstance\n} from '@firebase/util';\n\nimport { validateSetOptions } from '../util/input_validation';\n\nimport { Blob } from './blob';\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver\n} from './observer';\n\n/**\n * A persistence provider for either memory-only or IndexedDB persistence.\n * Mainly used to allow optional inclusion of IndexedDB code.\n */\nexport interface PersistenceProvider {\n enableIndexedDbPersistence(\n firestore: Firestore,\n forceOwnership: boolean\n ): Promise<void>;\n enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>;\n clearIndexedDbPersistence(firestore: Firestore): Promise<void>;\n}\n\n/**\n * The persistence provider included with the full Firestore SDK.\n */\nexport class IndexedDbPersistenceProvider implements PersistenceProvider {\n enableIndexedDbPersistence(\n firestore: Firestore,\n forceOwnership: boolean\n ): Promise<void> {\n return enableIndexedDbPersistence(firestore._delegate, { forceOwnership });\n }\n enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void> {\n return enableMultiTabIndexedDbPersistence(firestore._delegate);\n }\n clearIndexedDbPersistence(firestore: Firestore): Promise<void> {\n return clearIndexedDbPersistence(firestore._delegate);\n }\n}\n\n/**\n * Compat class for Firestore. Exposes Firestore Legacy API, but delegates\n * to the functional API of firestore-exp.\n */\nexport class Firestore\n implements PublicFirestore, FirebaseService, Compat<ExpFirestore>\n{\n _appCompat?: FirebaseApp;\n constructor(\n databaseIdOrApp: _DatabaseId | FirebaseApp,\n readonly _delegate: ExpFirestore,\n private _persistenceProvider: PersistenceProvider\n ) {\n if (!(databaseIdOrApp instanceof _DatabaseId)) {\n this._appCompat = databaseIdOrApp as FirebaseApp;\n }\n }\n\n get _databaseId(): _DatabaseId {\n return this._delegate._databaseId;\n }\n\n settings(settingsLiteral: PublicSettings): void {\n const currentSettings = this._delegate._getSettings();\n if (\n !settingsLiteral.merge &&\n currentSettings.host !== settingsLiteral.host\n ) {\n _logWarn(\n 'You are overriding the original host. If you did not intend ' +\n 'to override your settings, use {merge: true}.'\n );\n }\n\n if (settingsLiteral.merge) {\n settingsLiteral = {\n ...currentSettings,\n ...settingsLiteral\n };\n // Remove the property from the settings once the merge is completed\n delete settingsLiteral.merge;\n }\n\n this._delegate._setSettings(settingsLiteral);\n }\n\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n ): void {\n connectFirestoreEmulator(this._delegate, host, port, options);\n }\n\n enableNetwork(): Promise<void> {\n return enableNetwork(this._delegate);\n }\n\n disableNetwork(): Promise<void> {\n return disableNetwork(this._delegate);\n }\n\n enablePersistence(settings?: PublicPersistenceSettings): Promise<void> {\n let synchronizeTabs = false;\n let experimentalForceOwningTab = false;\n\n if (settings) {\n synchronizeTabs = !!settings.synchronizeTabs;\n experimentalForceOwningTab = !!settings.experimentalForceOwningTab;\n\n _validateIsNotUsedTogether(\n 'synchronizeTabs',\n synchronizeTabs,\n 'experimentalForceOwningTab',\n experimentalForceOwningTab\n );\n }\n\n return synchronizeTabs\n ? this._persistenceProvider.enableMultiTabIndexedDbPersistence(this)\n : this._persistenceProvider.enableIndexedDbPersistence(\n this,\n experimentalForceOwningTab\n );\n }\n\n clearPersistence(): Promise<void> {\n return this._persistenceProvider.clearIndexedDbPersistence(this);\n }\n\n terminate(): Promise<void> {\n if (this._appCompat) {\n (this._appCompat as _FirebaseApp)._removeServiceInstance(\n 'firestore-compat'\n );\n (this._appCompat as _FirebaseApp)._removeServiceInstance('firestore');\n }\n return this._delegate._delete();\n }\n\n waitForPendingWrites(): Promise<void> {\n return waitForPendingWrites(this._delegate);\n }\n\n onSnapshotsInSync(observer: PartialObserver<void>): Unsubscribe;\n onSnapshotsInSync(onSync: () => void): Unsubscribe;\n onSnapshotsInSync(arg: unknown): Unsubscribe {\n return onSnapshotsInSync(this._delegate, arg as PartialObserver<void>);\n }\n\n get app(): FirebaseApp {\n if (!this._appCompat) {\n throw new FirestoreError(\n 'failed-precondition',\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._appCompat as FirebaseApp;\n }\n\n INTERNAL = {\n delete: () => this.terminate()\n };\n\n collection(pathString: string): PublicCollectionReference {\n try {\n return new CollectionReference(\n this,\n collection(this._delegate, pathString)\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collection()',\n 'Firestore.collection()'\n );\n }\n }\n\n doc(pathString: string): PublicDocumentReference {\n try {\n return new DocumentReference(this, doc(this._delegate, pathString));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'doc()', 'Firestore.doc()');\n }\n }\n\n collectionGroup(collectionId: string): PublicQuery {\n try {\n return new Query(this, collectionGroup(this._delegate, collectionId));\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collectionGroup()',\n 'Firestore.collectionGroup()'\n );\n }\n }\n\n runTransaction<T>(\n updateFunction: (transaction: PublicTransaction) => Promise<T>\n ): Promise<T> {\n return runTransaction(this._delegate, transaction =>\n updateFunction(new Transaction(this, transaction))\n );\n }\n\n batch(): PublicWriteBatch {\n ensureFirestoreConfigured(this._delegate);\n return new WriteBatch(\n new ExpWriteBatch(this._delegate, mutations =>\n executeWrite(this._delegate, mutations)\n )\n );\n }\n\n loadBundle(\n bundleData: ArrayBuffer | ReadableStream<Uint8Array> | string\n ): LoadBundleTask {\n return loadBundle(this._delegate, bundleData);\n }\n\n namedQuery(name: string): Promise<PublicQuery<DocumentData> | null> {\n return namedQuery(this._delegate, name).then(expQuery => {\n if (!expQuery) {\n return null;\n }\n return new Query(\n this,\n // We can pass `expQuery` here directly since named queries don't have a UserDataConverter.\n // Otherwise, we would have to create a new ExpQuery and pass the old UserDataConverter.\n expQuery\n );\n });\n }\n}\n\nexport class UserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: _ByteString): Blob {\n return new Blob(new Bytes(bytes));\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return DocumentReference.forKey(key, this.firestore, /* converter= */ null);\n }\n}\n\nexport function setLogLevel(level: PublicLogLevel): void {\n setClientLogLevel(level);\n}\n\n/**\n * A reference to a transaction.\n */\nexport class Transaction implements PublicTransaction, Compat<ExpTransaction> {\n private _userDataWriter: UserDataWriter;\n\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpTransaction\n ) {\n this._userDataWriter = new UserDataWriter(_firestore);\n }\n\n get<T>(\n documentRef: PublicDocumentReference<T>\n ): Promise<PublicDocumentSnapshot<T>> {\n const ref = castReference(documentRef);\n return this._delegate\n .get(ref)\n .then(\n result =>\n new DocumentSnapshot(\n this._firestore,\n new ExpDocumentSnapshot<T>(\n this._firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n ref.converter\n )\n )\n );\n }\n\n set<T>(\n documentRef: DocumentReference<T>,\n data: Partial<T>,\n options: PublicSetOptions\n ): Transaction;\n set<T>(documentRef: DocumentReference<T>, data: T): Transaction;\n set<T>(\n documentRef: PublicDocumentReference<T>,\n data: T | Partial<T>,\n options?: PublicSetOptions\n ): Transaction {\n const ref = castReference(documentRef);\n if (options) {\n validateSetOptions('Transaction.set', options);\n this._delegate.set(ref, data as PartialWithFieldValue<T>, options);\n } else {\n this._delegate.set(ref, data as WithFieldValue<T>);\n }\n return this;\n }\n\n update(\n documentRef: PublicDocumentReference<unknown>,\n data: PublicUpdateData\n ): Transaction;\n update(\n documentRef: PublicDocumentReference<unknown>,\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction;\n update(\n documentRef: PublicDocumentReference<unknown>,\n dataOrField: unknown,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction {\n const ref = castReference(documentRef);\n if (arguments.length === 2) {\n this._delegate.update(ref, dataOrField as PublicUpdateData);\n } else {\n this._delegate.update(\n ref,\n dataOrField as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n\n return this;\n }\n\n delete(documentRef: PublicDocumentReference<unknown>): Transaction {\n const ref = castReference(documentRef);\n this._delegate.delete(ref);\n return this;\n }\n}\n\nexport class WriteBatch implements PublicWriteBatch, Compat<ExpWriteBatch> {\n constructor(readonly _delegate: ExpWriteBatch) {}\n set<T>(\n documentRef: DocumentReference<T>,\n data: Partial<T>,\n options: PublicSetOptions\n ): WriteBatch;\n set<T>(documentRef: DocumentReference<T>, data: T): WriteBatch;\n set<T>(\n documentRef: PublicDocumentReference<T>,\n data: T | Partial<T>,\n options?: PublicSetOptions\n ): WriteBatch {\n const ref = castReference(documentRef);\n if (options) {\n validateSetOptions('WriteBatch.set', options);\n this._delegate.set(ref, data as PartialWithFieldValue<T>, options);\n } else {\n this._delegate.set(ref, data as WithFieldValue<T>);\n }\n return this;\n }\n\n update(\n documentRef: PublicDocumentReference<unknown>,\n data: PublicUpdateData\n ): WriteBatch;\n update(\n documentRef: PublicDocumentReference<unknown>,\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: PublicDocumentReference<unknown>,\n dataOrField: string | PublicFieldPath | PublicUpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n const ref = castReference(documentRef);\n if (arguments.length === 2) {\n this._delegate.update(ref, dataOrField as PublicUpdateData);\n } else {\n this._delegate.update(\n ref,\n dataOrField as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n return this;\n }\n\n delete(documentRef: PublicDocumentReference<unknown>): WriteBatch {\n const ref = castReference(documentRef);\n this._delegate.delete(ref);\n return this;\n }\n\n commit(): Promise<void> {\n return this._delegate.commit();\n }\n}\n\n/**\n * Wraps a `PublicFirestoreDataConverter` translating the types from the\n * experimental SDK into corresponding types from the Classic SDK before passing\n * them to the wrapped converter.\n */\nclass FirestoreDataConverter<U>\n implements\n ModularFirestoreDataConverter<U>,\n Compat<PublicFirestoreDataConverter<U>>\n{\n private static readonly INSTANCES = new WeakMap();\n\n private constructor(\n private readonly _firestore: Firestore,\n private readonly _userDataWriter: UserDataWriter,\n readonly _delegate: PublicFirestoreDataConverter<U>\n ) {}\n\n fromFirestore(\n snapshot: ExpQueryDocumentSnapshot,\n options?: PublicSnapshotOptions\n ): U {\n const expSnapshot = new ExpQueryDocumentSnapshot(\n this._firestore._delegate,\n this._userDataWriter,\n snapshot._key,\n snapshot._document,\n snapshot.metadata,\n /* converter= */ null\n );\n return this._delegate.fromFirestore(\n new QueryDocumentSnapshot(this._firestore, expSnapshot),\n options ?? {}\n );\n }\n\n toFirestore(modelObject: WithFieldValue<U>): PublicDocumentData;\n toFirestore(\n modelObject: PartialWithFieldValue<U>,\n options: PublicSetOptions\n ): PublicDocumentData;\n toFirestore(\n modelObject: WithFieldValue<U> | PartialWithFieldValue<U>,\n options?: PublicSetOptions\n ): PublicDocumentData {\n if (!options) {\n return this._delegate.toFirestore(modelObject as U);\n } else {\n return this._delegate.toFirestore(modelObject as Partial<U>, options);\n }\n }\n\n // Use the same instance of `FirestoreDataConverter` for the given instances\n // of `Firestore` and `PublicFirestoreDataConverter` so that isEqual() will\n // compare equal for two objects created with the same converter instance.\n static getInstance<U>(\n firestore: Firestore,\n converter: PublicFirestoreDataConverter<U>\n ): FirestoreDataConverter<U> {\n const converterMapByFirestore = FirestoreDataConverter.INSTANCES;\n let untypedConverterByConverter = converterMapByFirestore.get(firestore);\n if (!untypedConverterByConverter) {\n untypedConverterByConverter = new WeakMap();\n converterMapByFirestore.set(firestore, untypedConverterByConverter);\n }\n\n let instance = untypedConverterByConverter.get(converter);\n if (!instance) {\n instance = new FirestoreDataConverter(\n firestore,\n new UserDataWriter(firestore),\n converter\n );\n untypedConverterByConverter.set(converter, instance);\n }\n\n return instance;\n }\n}\n\n/**\n * A reference to a particular document in a collection in the database.\n */\nexport class DocumentReference<T = PublicDocumentData>\n implements PublicDocumentReference<T>, Compat<ExpDocumentReference<T>>\n{\n private _userDataWriter: UserDataWriter;\n\n constructor(\n readonly firestore: Firestore,\n readonly _delegate: ExpDocumentReference<T>\n ) {\n this._userDataWriter = new UserDataWriter(firestore);\n }\n\n static forPath<U>(\n path: _ResourcePath,\n firestore: Firestore,\n converter: ModularFirestoreDataConverter<U> | null\n ): DocumentReference<U> {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(\n '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(\n firestore,\n new ExpDocumentReference(\n firestore._delegate,\n converter,\n new _DocumentKey(path)\n )\n );\n }\n\n static forKey<U>(\n key: _DocumentKey,\n firestore: Firestore,\n converter: ModularFirestoreDataConverter<U> | null\n ): DocumentReference<U> {\n return new DocumentReference(\n firestore,\n new ExpDocumentReference(firestore._delegate, converter, key)\n );\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get parent(): PublicCollectionReference<T> {\n return new CollectionReference(this.firestore, this._delegate.parent);\n }\n\n get path(): string {\n return this._delegate.path;\n }\n\n collection(\n pathString: string\n ): PublicCollectionReference<PublicDocumentData> {\n try {\n return new CollectionReference(\n this.firestore,\n collection(this._delegate, pathString)\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collection()',\n 'DocumentReference.collection()'\n );\n }\n }\n\n isEqual(other: PublicDocumentReference<T>): boolean {\n other = getModularInstance<PublicDocumentReference<T>>(other);\n\n if (!(other instanceof ExpDocumentReference)) {\n return false;\n }\n return refEqual(this._delegate, other);\n }\n\n set(value: Partial<T>, options: PublicSetOptions): Promise<void>;\n set(value: T): Promise<void>;\n set(value: T | Partial<T>, options?: PublicSetOptions): Promise<void> {\n options = validateSetOptions('DocumentReference.set', options);\n try {\n if (options) {\n return setDoc(\n this._delegate,\n value as PartialWithFieldValue<T>,\n options\n );\n } else {\n return setDoc(this._delegate, value as WithFieldValue<T>);\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'setDoc()',\n 'DocumentReference.set()'\n );\n }\n }\n\n update(value: PublicUpdateData): Promise<void>;\n update(\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void>;\n update(\n fieldOrUpdateData: string | PublicFieldPath | PublicUpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void> {\n try {\n if (arguments.length === 1) {\n return updateDoc(this._delegate, fieldOrUpdateData as PublicUpdateData);\n } else {\n return updateDoc(\n this._delegate,\n fieldOrUpdateData as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'updateDoc()',\n 'DocumentReference.update()'\n );\n }\n }\n\n delete(): Promise<void> {\n return deleteDoc(this._delegate);\n }\n\n onSnapshot(observer: PartialObserver<PublicDocumentSnapshot<T>>): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n observer: PartialObserver<PublicDocumentSnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<PublicDocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n onNext: NextFn<PublicDocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n const options = extractSnapshotOptions(args);\n const observer = wrapObserver<DocumentSnapshot<T>, ExpDocumentSnapshot<T>>(\n args,\n result =>\n new DocumentSnapshot(\n this.firestore,\n new ExpDocumentSnapshot(\n this.firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n this._delegate.converter\n )\n )\n );\n return onSnapshot(this._delegate, options, observer);\n }\n\n get(options?: PublicGetOptions): Promise<PublicDocumentSnapshot<T>> {\n let snap: Promise<ExpDocumentSnapshot<T>>;\n if (options?.source === 'cache') {\n snap = getDocFromCache(this._delegate);\n } else if (options?.source === 'server') {\n snap = getDocFromServer(this._delegate);\n } else {\n snap = getDoc(this._delegate);\n }\n\n return snap.then(\n result =>\n new DocumentSnapshot(\n this.firestore,\n new ExpDocumentSnapshot(\n this.firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n this._delegate.converter\n )\n )\n );\n }\n\n withConverter(converter: null): PublicDocumentReference<PublicDocumentData>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U>\n ): PublicDocumentReference<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): PublicDocumentReference<U> {\n return new DocumentReference<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpDocumentReference<U>)\n );\n }\n}\n\n/**\n * Replaces the function name in an error thrown by the firestore-exp API\n * with the function names used in the classic API.\n */\nfunction replaceFunctionName(\n e: Error,\n original: string | RegExp,\n updated: string\n): Error {\n e.message = e.message.replace(original, updated);\n return e;\n}\n\n/**\n * Iterates the list of arguments from an `onSnapshot` call and returns the\n * first argument that may be an `SnapshotListenOptions` object. Returns an\n * empty object if none is found.\n */\nexport function extractSnapshotOptions(\n args: unknown[]\n): PublicSnapshotListenOptions {\n for (const arg of args) {\n if (typeof arg === 'object' && !isPartialObserver(arg)) {\n return arg as PublicSnapshotListenOptions;\n }\n }\n return {};\n}\n\n/**\n * Creates an observer that can be passed to the firestore-exp SDK. The\n * observer converts all observed values into the format expected by the classic\n * SDK.\n *\n * @param args - The list of arguments from an `onSnapshot` call.\n * @param wrapper - The function that converts the firestore-exp type into the\n * type used by this shim.\n */\nexport function wrapObserver<CompatType, ExpType>(\n args: unknown[],\n wrapper: (val: ExpType) => CompatType\n): PartialObserver<ExpType> {\n let userObserver: PartialObserver<CompatType>;\n if (isPartialObserver(args[0])) {\n userObserver = args[0] as PartialObserver<CompatType>;\n } else if (isPartialObserver(args[1])) {\n userObserver = args[1];\n } else if (typeof args[0] === 'function') {\n userObserver = {\n next: args[0] as NextFn<CompatType> | undefined,\n error: args[1] as ErrorFn | undefined,\n complete: args[2] as CompleteFn | undefined\n };\n } else {\n userObserver = {\n next: args[1] as NextFn<CompatType> | undefined,\n error: args[2] as ErrorFn | undefined,\n complete: args[3] as CompleteFn | undefined\n };\n }\n\n return {\n next: val => {\n if (userObserver!.next) {\n userObserver!.next(wrapper(val));\n }\n },\n error: userObserver.error?.bind(userObserver),\n complete: userObserver.complete?.bind(userObserver)\n };\n}\n\n/**\n * Options interface that can be provided to configure the deserialization of\n * DocumentSnapshots.\n */\nexport interface SnapshotOptions extends PublicSnapshotOptions {}\n\nexport class DocumentSnapshot<T = PublicDocumentData>\n implements PublicDocumentSnapshot<T>, Compat<ExpDocumentSnapshot<T>>\n{\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpDocumentSnapshot<T>\n ) {}\n\n get ref(): DocumentReference<T> {\n return new DocumentReference<T>(this._firestore, this._delegate.ref);\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get metadata(): SnapshotMetadata {\n return this._delegate.metadata;\n }\n\n get exists(): boolean {\n return this._delegate.exists();\n }\n\n data(options?: PublicSnapshotOptions): T | undefined {\n return this._delegate.data(options);\n }\n\n get(\n fieldPath: string | PublicFieldPath,\n options?: PublicSnapshotOptions\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): any {\n return this._delegate.get(fieldPath as string | ExpFieldPath, options);\n }\n\n isEqual(other: DocumentSnapshot<T>): boolean {\n return snapshotEqual(this._delegate, other._delegate);\n }\n}\n\nexport class QueryDocumentSnapshot<T = PublicDocumentData>\n extends DocumentSnapshot<T>\n implements PublicQueryDocumentSnapshot<T>\n{\n data(options?: PublicSnapshotOptions): T {\n const data = this._delegate.data(options);\n if (this._delegate._converter) {\n // Undefined is a possible valid value from converter.\n return data as T;\n } else {\n _debugAssert(\n data !== undefined,\n 'Document in a QueryDocumentSnapshot should exist'\n );\n return data;\n }\n }\n}\n\nexport class Query<T = PublicDocumentData>\n implements PublicQuery<T>, Compat<ExpQuery<T>>\n{\n private readonly _userDataWriter: UserDataWriter;\n\n constructor(readonly firestore: Firestore, readonly _delegate: ExpQuery<T>) {\n this._userDataWriter = new UserDataWriter(firestore);\n }\n\n where(\n fieldPath: string | _FieldPath,\n opStr: PublicWhereFilterOp,\n value: unknown\n ): Query<T> {\n try {\n // The \"as string\" cast is a little bit of a hack. `where` accepts the\n // FieldPath Compat type as input, but is not typed as such in order to\n // not expose this via our public typings file.\n return new Query<T>(\n this.firestore,\n query(this._delegate, where(fieldPath as string, opStr, value))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n /(orderBy|where)\\(\\)/,\n 'Query.$1()'\n );\n }\n }\n\n orderBy(\n fieldPath: string | _FieldPath,\n directionStr?: PublicOrderByDirection\n ): Query<T> {\n try {\n // The \"as string\" cast is a little bit of a hack. `orderBy` accepts the\n // FieldPath Compat type as input, but is not typed as such in order to\n // not expose this via our public typings file.\n return new Query<T>(\n this.firestore,\n query(this._delegate, orderBy(fieldPath as string, directionStr))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n /(orderBy|where)\\(\\)/,\n 'Query.$1()'\n );\n }\n }\n\n limit(n: number): Query<T> {\n try {\n return new Query<T>(this.firestore, query(this._delegate, limit(n)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'limit()', 'Query.limit()');\n }\n }\n\n limitToLast(n: number): Query<T> {\n try {\n return new Query<T>(\n this.firestore,\n query(this._delegate, limitToLast(n))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'limitToLast()',\n 'Query.limitToLast()'\n );\n }\n }\n\n startAt(...args: any[]): Query<T> {\n try {\n return new Query(this.firestore, query(this._delegate, startAt(...args)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'startAt()', 'Query.startAt()');\n }\n }\n\n startAfter(...args: any[]): Query<T> {\n try {\n return new Query(\n this.firestore,\n query(this._delegate, startAfter(...args))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'startAfter()',\n 'Query.startAfter()'\n );\n }\n }\n\n endBefore(...args: any[]): Query<T> {\n try {\n return new Query(\n this.firestore,\n query(this._delegate, endBefore(...args))\n );\n } catch (e) {\n throw replaceFunctionName(e as Error, 'endBefore()', 'Query.endBefore()');\n }\n }\n\n endAt(...args: any[]): Query<T> {\n try {\n return new Query(this.firestore, query(this._delegate, endAt(...args)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'endAt()', 'Query.endAt()');\n }\n }\n\n isEqual(other: PublicQuery<T>): boolean {\n return queryEqual(this._delegate, (other as Query<T>)._delegate);\n }\n\n get(options?: PublicGetOptions): Promise<QuerySnapshot<T>> {\n let query: Promise<ExpQuerySnapshot<T>>;\n if (options?.source === 'cache') {\n query = getDocsFromCache(this._delegate);\n } else if (options?.source === 'server') {\n query = getDocsFromServer(this._delegate);\n } else {\n query = getDocs(this._delegate);\n }\n return query.then(\n result =>\n new QuerySnapshot(\n this.firestore,\n new ExpQuerySnapshot<T>(\n this.firestore._delegate,\n this._userDataWriter,\n this._delegate,\n result._snapshot\n )\n )\n );\n }\n\n onSnapshot(observer: PartialObserver<PublicQuerySnapshot<T>>): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n observer: PartialObserver<PublicQuerySnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<PublicQuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n onNext: NextFn<PublicQuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n const options = extractSnapshotOptions(args);\n const observer = wrapObserver<QuerySnapshot<T>, ExpQuerySnapshot<T>>(\n args,\n snap =>\n new QuerySnapshot(\n this.firestore,\n new ExpQuerySnapshot<T>(\n this.firestore._delegate,\n this._userDataWriter,\n this._delegate,\n snap._snapshot\n )\n )\n );\n return onSnapshot(this._delegate, options, observer);\n }\n\n withConverter(converter: null): Query<PublicDocumentData>;\n withConverter<U>(converter: PublicFirestoreDataConverter<U>): Query<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): Query<U> {\n return new Query<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpQuery<U>)\n );\n }\n}\n\nexport class DocumentChange<T = PublicDocumentData>\n implements PublicDocumentChange<T>, Compat<ExpDocumentChange<T>>\n{\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpDocumentChange<T>\n ) {}\n\n get type(): PublicDocumentChangeType {\n return this._delegate.type;\n }\n\n get doc(): QueryDocumentSnapshot<T> {\n return new QueryDocumentSnapshot<T>(this._firestore, this._delegate.doc);\n }\n\n get oldIndex(): number {\n return this._delegate.oldIndex;\n }\n\n get newIndex(): number {\n return this._delegate.newIndex;\n }\n}\n\nexport class QuerySnapshot<T = PublicDocumentData>\n implements PublicQuerySnapshot<T>, Compat<ExpQuerySnapshot<T>>\n{\n constructor(\n readonly _firestore: Firestore,\n readonly _delegate: ExpQuerySnapshot<T>\n ) {}\n\n get query(): Query<T> {\n return new Query(this._firestore, this._delegate.query);\n }\n\n get metadata(): SnapshotMetadata {\n return this._delegate.metadata;\n }\n\n get size(): number {\n return this._delegate.size;\n }\n\n get empty(): boolean {\n return this._delegate.empty;\n }\n\n get docs(): Array<QueryDocumentSnapshot<T>> {\n return this._delegate.docs.map(\n doc => new QueryDocumentSnapshot<T>(this._firestore, doc)\n );\n }\n\n docChanges(\n options?: PublicSnapshotListenOptions\n ): Array<PublicDocumentChange<T>> {\n return this._delegate\n .docChanges(options)\n .map(docChange => new DocumentChange<T>(this._firestore, docChange));\n }\n\n forEach(\n callback: (result: QueryDocumentSnapshot<T>) => void,\n thisArg?: unknown\n ): void {\n this._delegate.forEach(snapshot => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot(this._firestore, snapshot)\n );\n });\n }\n\n isEqual(other: QuerySnapshot<T>): boolean {\n return snapshotEqual(this._delegate, other._delegate);\n }\n}\n\nexport class CollectionReference<T = PublicDocumentData>\n extends Query<T>\n implements PublicCollectionReference<T>\n{\n constructor(\n readonly firestore: Firestore,\n readonly _delegate: ExpCollectionReference<T>\n ) {\n super(firestore, _delegate);\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get path(): string {\n return this._delegate.path;\n }\n\n get parent(): DocumentReference<PublicDocumentData> | null {\n const docRef = this._delegate.parent;\n return docRef ? new DocumentReference(this.firestore, docRef) : null;\n }\n\n doc(documentPath?: string): DocumentReference<T> {\n try {\n if (documentPath === undefined) {\n // Call `doc` without `documentPath` if `documentPath` is `undefined`\n // as `doc` validates the number of arguments to prevent users from\n // accidentally passing `undefined`.\n return new DocumentReference(this.firestore, doc(this._delegate));\n } else {\n return new DocumentReference(\n this.firestore,\n doc(this._delegate, documentPath)\n );\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'doc()',\n 'CollectionReference.doc()'\n );\n }\n }\n\n add(data: T): Promise<DocumentReference<T>> {\n return addDoc(this._delegate, data as WithFieldValue<T>).then(\n docRef => new DocumentReference(this.firestore, docRef)\n );\n }\n\n isEqual(other: CollectionReference<T>): boolean {\n return refEqual(this._delegate, other._delegate);\n }\n\n withConverter(converter: null): CollectionReference<PublicDocumentData>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U>\n ): CollectionReference<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): CollectionReference<U> {\n return new CollectionReference<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpCollectionReference<U>)\n );\n }\n}\n\nfunction castReference<T>(\n documentRef: PublicDocumentReference<T>\n): ExpDocumentReference<T> {\n return _cast<ExpDocumentReference<T>>(documentRef, ExpDocumentReference);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FieldPath as ExpFieldPath,\n _FieldPath as InternalFieldPath\n} from '@firebase/firestore';\nimport { FieldPath as PublicFieldPath } from '@firebase/firestore-types';\nimport { Compat, getModularInstance } from '@firebase/util';\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\n * single field name (referring to a top-level field in the document), or a list\n * of field names (referring to a nested field in the document).\n */\nexport class FieldPath implements PublicFieldPath, Compat<ExpFieldPath> {\n readonly _delegate: ExpFieldPath;\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 this._delegate = new ExpFieldPath(...fieldNames);\n }\n\n static documentId(): FieldPath {\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 return new FieldPath(InternalFieldPath.keyField().canonicalString());\n }\n\n isEqual(other: PublicFieldPath): boolean {\n other = getModularInstance(other);\n\n if (!(other instanceof ExpFieldPath)) {\n return false;\n }\n return this._delegate._internalPath.isEqual(other._internalPath);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n arrayRemove,\n arrayUnion,\n deleteField,\n FieldValue as FieldValue1,\n increment,\n serverTimestamp\n} from '@firebase/firestore';\nimport { FieldValue as PublicFieldValue } from '@firebase/firestore-types';\nimport { Compat } from '@firebase/util';\n\nexport class FieldValue implements PublicFieldValue, Compat<FieldValue1> {\n static serverTimestamp(): FieldValue {\n const delegate = serverTimestamp();\n delegate._methodName = 'FieldValue.serverTimestamp';\n return new FieldValue(delegate);\n }\n\n static delete(): FieldValue {\n const delegate = deleteField();\n delegate._methodName = 'FieldValue.delete';\n return new FieldValue(delegate);\n }\n\n static arrayUnion(...elements: unknown[]): FieldValue {\n const delegate = arrayUnion(...elements);\n delegate._methodName = 'FieldValue.arrayUnion';\n return new FieldValue(delegate);\n }\n\n static arrayRemove(...elements: unknown[]): FieldValue {\n const delegate = arrayRemove(...elements);\n delegate._methodName = 'FieldValue.arrayRemove';\n return new FieldValue(delegate);\n }\n\n static increment(n: number): FieldValue {\n const delegate = increment(n);\n delegate._methodName = 'FieldValue.increment';\n return new FieldValue(delegate);\n }\n\n constructor(readonly _delegate: FieldValue1) {}\n\n isEqual(other: FieldValue): boolean {\n return this._delegate.isEqual(other._delegate);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\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\n/**\n * Takes data and encodes it in a JSON-friendly way, such that types such as\n * Date are preserved.\n * @internal\n * @param data - Data to encode.\n */\nexport function 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 (data instanceof Date) {\n return data.toISOString();\n }\n if (Array.isArray(data)) {\n return data.map(x => encode(x));\n }\n if (typeof data === 'function' || typeof data === 'object') {\n return mapValues(data!, x => 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/**\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 * @internal\n * @param json - JSON to convert.\n */\nexport function 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 => decode(x));\n }\n if (typeof json === 'function' || typeof json === 'object') {\n return mapValues(json!, x => decode(x));\n }\n // Anything else is safe to return.\n return json;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Functions.\n */\nexport const FUNCTIONS_TYPE = 'functions';\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FunctionsErrorCodeCore as FunctionsErrorCode } from './public-types';\nimport { decode } from './serializer';\nimport { HttpResponseBody } from './service';\nimport { FirebaseError } from '@firebase/util';\nimport { FUNCTIONS_TYPE } from './constants';\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 FunctionsError extends FirebaseError {\n constructor(\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 code: FunctionsErrorCode,\n message?: string,\n /**\n * Extra data to be converted to JSON and included in the error response.\n */\n readonly details?: unknown\n ) {\n super(`${FUNCTIONS_TYPE}/${code}`, message || '');\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): 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 FunctionsError('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 = decode(details);\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 FunctionsError(code, description, details);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Provider } from '@firebase/component';\nimport {\n AppCheckInternalComponentName,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport {\n MessagingInternal,\n MessagingInternalComponentName\n} from '@firebase/messaging-interop-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\n\n/**\n * The metadata that should be supplied with function calls.\n * @internal\n */\nexport interface Context {\n authToken?: string;\n messagingToken?: string;\n appCheckToken: string | null;\n}\n\n/**\n * Helper class to get metadata that should be included with a function call.\n * @internal\n */\nexport class ContextProvider {\n private auth: FirebaseAuthInternal | null = null;\n private messaging: MessagingInternal | null = null;\n private appCheck: FirebaseAppCheckInternal | null = null;\n constructor(\n authProvider: Provider<FirebaseAuthInternalName>,\n messagingProvider: Provider<MessagingInternalComponentName>,\n appCheckProvider: Provider<AppCheckInternalComponentName>\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 if (!this.appCheck) {\n appCheckProvider.get().then(\n appCheck => (this.appCheck = appCheck),\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 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 getMessagingToken(): 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 await 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 getAppCheckToken(\n limitedUseAppCheckTokens?: boolean\n ): Promise<string | null> {\n if (this.appCheck) {\n const result = limitedUseAppCheckTokens\n ? await this.appCheck.getLimitedUseToken()\n : await this.appCheck.getToken();\n if (result.error) {\n // Do not send the App Check header to the functions endpoint if\n // there was an error from the App Check exchange endpoint. The App\n // Check SDK will already have logged the error to console.\n return null;\n }\n return result.token;\n }\n return null;\n }\n\n async getContext(limitedUseAppCheckTokens?: boolean): Promise<Context> {\n const authToken = await this.getAuthToken();\n const messagingToken = await this.getMessagingToken();\n const appCheckToken = await this.getAppCheckToken(limitedUseAppCheckTokens);\n return { authToken, messagingToken, appCheckToken };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport {\n HttpsCallable,\n HttpsCallableResult,\n HttpsCallableOptions\n} from './public-types';\nimport { _errorForResponse, FunctionsError } from './error';\nimport { ContextProvider } from './context';\nimport { encode, decode } from './serializer';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { MessagingInternalComponentName } from '@firebase/messaging-interop-types';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\n\nexport const DEFAULT_REGION = 'us-central1';\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\ninterface CancellablePromise<T> {\n promise: Promise<T>;\n cancel: () => void;\n}\n\n/**\n * Returns a Promise that will be rejected after the given duration.\n * The error will be of type FunctionsError.\n *\n * @param millis Number of milliseconds to wait before rejecting.\n */\nfunction failAfter(millis: number): CancellablePromise<never> {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let timer: any | null = null;\n return {\n promise: new Promise((_, reject) => {\n timer = setTimeout(() => {\n reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));\n }, millis);\n }),\n cancel: () => {\n if (timer) {\n clearTimeout(timer);\n }\n }\n };\n}\n\n/**\n * The main class for the Firebase Functions SDK.\n * @internal\n */\nexport class FunctionsService implements _FirebaseService {\n readonly contextProvider: ContextProvider;\n emulatorOrigin: string | null = null;\n cancelAllRequests: Promise<void>;\n deleteService!: () => Promise<void>;\n region: string;\n customDomain: string | null;\n\n /**\n * Creates a new Functions service for the given app.\n * @param app - The FirebaseApp to use.\n */\n constructor(\n readonly app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n messagingProvider: Provider<MessagingInternalComponentName>,\n appCheckProvider: Provider<AppCheckInternalComponentName>,\n regionOrCustomDomain: string = DEFAULT_REGION,\n readonly fetchImpl: typeof fetch\n ) {\n this.contextProvider = new ContextProvider(\n authProvider,\n messagingProvider,\n appCheckProvider\n );\n // Cancels all ongoing requests when resolved.\n this.cancelAllRequests = new Promise(resolve => {\n this.deleteService = () => {\n return Promise.resolve(resolve());\n };\n });\n\n // Resolve the region or custom domain overload by attempting to parse it.\n try {\n const url = new URL(regionOrCustomDomain);\n this.customDomain = url.origin;\n this.region = DEFAULT_REGION;\n } catch (e) {\n this.customDomain = null;\n this.region = regionOrCustomDomain;\n }\n }\n\n _delete(): Promise<void> {\n return this.deleteService();\n }\n\n /**\n * Returns the URL for a callable with the given name.\n * @param name - The name of the callable.\n * @internal\n */\n _url(name: string): string {\n const projectId = this.app.options.projectId;\n if (this.emulatorOrigin !== null) {\n const origin = this.emulatorOrigin;\n return `${origin}/${projectId}/${this.region}/${name}`;\n }\n\n if (this.customDomain !== null) {\n return `${this.customDomain}/${name}`;\n }\n\n return `https://${this.region}-${projectId}.cloudfunctions.net/${name}`;\n }\n}\n\n/**\n * Modify this instance to communicate with the Cloud Functions emulator.\n *\n * Note: this must be called before this instance has been used to do any operations.\n *\n * @param host The emulator host (ex: localhost)\n * @param port The emulator port (ex: 5001)\n * @public\n */\nexport function connectFunctionsEmulator(\n functionsInstance: FunctionsService,\n host: string,\n port: number\n): void {\n functionsInstance.emulatorOrigin = `http://${host}:${port}`;\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 * @public\n */\nexport function httpsCallable<RequestData, ResponseData>(\n functionsInstance: FunctionsService,\n name: string,\n options?: HttpsCallableOptions\n): HttpsCallable<RequestData, ResponseData> {\n return (data => {\n return call(functionsInstance, name, data, options || {});\n }) as HttpsCallable<RequestData, ResponseData>;\n}\n\n/**\n * Returns a reference to the callable https trigger with the given url.\n * @param url - The url of the trigger.\n * @public\n */\nexport function httpsCallableFromURL<RequestData, ResponseData>(\n functionsInstance: FunctionsService,\n url: string,\n options?: HttpsCallableOptions\n): HttpsCallable<RequestData, ResponseData> {\n return (data => {\n return callAtURL(functionsInstance, url, data, options || {});\n }) as HttpsCallable<RequestData, ResponseData>;\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 */\nasync function postJSON(\n url: string,\n body: unknown,\n headers: { [key: string]: string },\n fetchImpl: typeof fetch\n): Promise<HttpResponse> {\n headers['Content-Type'] = 'application/json';\n\n let response: Response;\n try {\n response = await fetchImpl(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: HttpResponseBody | 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 */\nfunction call(\n functionsInstance: FunctionsService,\n name: string,\n data: unknown,\n options: HttpsCallableOptions\n): Promise<HttpsCallableResult> {\n const url = functionsInstance._url(name);\n return callAtURL(functionsInstance, url, data, options);\n}\n\n/**\n * Calls a callable function asynchronously and returns the result.\n * @param url The url of the callable trigger.\n * @param data The data to pass as params to the function.s\n */\nasync function callAtURL(\n functionsInstance: FunctionsService,\n url: string,\n data: unknown,\n options: HttpsCallableOptions\n): Promise<HttpsCallableResult> {\n // Encode any special types, such as dates, in the input data.\n data = encode(data);\n const body = { data };\n\n // Add a header for the authToken.\n const headers: { [key: string]: string } = {};\n const context = await functionsInstance.contextProvider.getContext(\n options.limitedUseAppCheckTokens\n );\n if (context.authToken) {\n headers['Authorization'] = 'Bearer ' + context.authToken;\n }\n if (context.messagingToken) {\n headers['Firebase-Instance-ID-Token'] = context.messagingToken;\n }\n if (context.appCheckToken !== null) {\n headers['X-Firebase-AppCheck'] = context.appCheckToken;\n }\n\n // Default timeout to 70s, but let the options override it.\n const timeout = options.timeout || 70000;\n\n const failAfterHandle = failAfter(timeout);\n const response = await Promise.race([\n postJSON(url, body, headers, functionsInstance.fetchImpl),\n failAfterHandle.promise,\n functionsInstance.cancelAllRequests\n ]);\n\n // Always clear the failAfter timeout\n failAfterHandle.cancel();\n\n // If service was deleted, interrupted response throws an error.\n if (!response) {\n throw new FunctionsError(\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(response.status, response.json);\n if (error) {\n throw error;\n }\n\n if (!response.json) {\n throw new FunctionsError('internal', 'Response is not valid JSON object.');\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 FunctionsError('internal', 'Response is missing data field.');\n }\n\n // Decode any special types, such as dates, in the returned data.\n const decodedData = decode(responseData);\n\n return { data: decodedData };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport { FUNCTIONS_TYPE } from './constants';\n\nimport { Provider } from '@firebase/component';\nimport { Functions, HttpsCallableOptions, HttpsCallable } from './public-types';\nimport {\n FunctionsService,\n DEFAULT_REGION,\n connectFunctionsEmulator as _connectFunctionsEmulator,\n httpsCallable as _httpsCallable,\n httpsCallableFromURL as _httpsCallableFromURL\n} from './service';\nimport {\n getModularInstance,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\n\nexport * from './public-types';\n\n/**\n * Returns a {@link Functions} instance for the given app.\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n * @param regionOrCustomDomain - one of:\n * a) The region the callable functions are located in (ex: us-central1)\n * b) A custom domain hosting the callable functions (ex: https://mydomain.com)\n * @public\n */\nexport function getFunctions(\n app: FirebaseApp = getApp(),\n regionOrCustomDomain: string = DEFAULT_REGION\n): Functions {\n // Dependencies\n const functionsProvider: Provider<'functions'> = _getProvider(\n getModularInstance(app),\n FUNCTIONS_TYPE\n );\n const functionsInstance = functionsProvider.getImmediate({\n identifier: regionOrCustomDomain\n });\n const emulator = getDefaultEmulatorHostnameAndPort('functions');\n if (emulator) {\n connectFunctionsEmulator(functionsInstance, ...emulator);\n }\n return functionsInstance;\n}\n\n/**\n * Modify this instance to communicate with the Cloud Functions emulator.\n *\n * Note: this must be called before this instance has been used to do any operations.\n *\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 5001)\n * @public\n */\nexport function connectFunctionsEmulator(\n functionsInstance: Functions,\n host: string,\n port: number\n): void {\n _connectFunctionsEmulator(\n getModularInstance<FunctionsService>(functionsInstance as FunctionsService),\n host,\n port\n );\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 * @public\n */\nexport function httpsCallable<RequestData = unknown, ResponseData = unknown>(\n functionsInstance: Functions,\n name: string,\n options?: HttpsCallableOptions\n): HttpsCallable<RequestData, ResponseData> {\n return _httpsCallable<RequestData, ResponseData>(\n getModularInstance<FunctionsService>(functionsInstance as FunctionsService),\n name,\n options\n );\n}\n\n/**\n * Returns a reference to the callable HTTPS trigger with the specified url.\n * @param url - The url of the trigger.\n * @public\n */\nexport function httpsCallableFromURL<\n RequestData = unknown,\n ResponseData = unknown\n>(\n functionsInstance: Functions,\n url: string,\n options?: HttpsCallableOptions\n): HttpsCallable<RequestData, ResponseData> {\n return _httpsCallableFromURL<RequestData, ResponseData>(\n getModularInstance<FunctionsService>(functionsInstance as FunctionsService),\n url,\n options\n );\n}\n","/**\n * Cloud Functions for Firebase\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerFunctions } from './config';\n\nexport * from './api';\nexport * from './public-types';\n\nregisterFunctions(fetch.bind(self));\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport { FunctionsService } from './service';\nimport {\n Component,\n ComponentType,\n InstanceFactory,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\n\nconst DEFAULT_REGION = 'us-central1';\n\nconst factory: InstanceFactory<'functions-compat'> = (\n container: ComponentContainer,\n { instanceIdentifier: regionOrCustomDomain }: InstanceFactoryOptions\n) => {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n const functionsServiceExp = container.getProvider('functions').getImmediate({\n identifier: regionOrCustomDomain ?? DEFAULT_REGION\n });\n\n return new FunctionsService(app, functionsServiceExp);\n};\n\nexport function registerFunctions(): void {\n const namespaceExports = {\n Functions: FunctionsService\n };\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component('functions-compat', factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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';\nexport const TAG = 'FirebaseMessaging: ';\nexport const MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST = 1000;\nexport const MAX_RETRIES = 3;\nexport const LOG_INTERVAL_IN_MS = 86400000; //24 hour\nexport const DEFAULT_BACKOFF_TIME_MS = 5000;\n\n// FCM log source name registered at Firelog: 'FCM_CLIENT_EVENT_LOGGING'. It uniquely identifies\n// FCM's logging configuration.\nexport const FCM_LOG_SOURCE = 1249;\n\n// Defined as in proto/messaging_event.proto. Neglecting fields that are supported.\nexport const SDK_PLATFORM_WEB = 3;\nexport const EVENT_MESSAGE_DELIVERED = 1;\n\nexport enum MessageType {\n DATA_MESSAGE = 1,\n DISPLAY_NOTIFICATION = 3\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\n\nimport {\n CONSOLE_CAMPAIGN_ANALYTICS_ENABLED,\n CONSOLE_CAMPAIGN_ID,\n CONSOLE_CAMPAIGN_NAME,\n CONSOLE_CAMPAIGN_TIME\n} from '../util/constants';\n\nexport interface MessagePayloadInternal {\n notification?: NotificationPayloadInternal;\n data?: unknown;\n fcmOptions?: FcmOptionsInternal;\n messageType?: MessageType;\n isFirebaseMessaging?: boolean;\n from: string;\n fcmMessageId: string;\n productId: number;\n // eslint-disable-next-line camelcase\n collapse_key: string;\n}\n\nexport interface NotificationPayloadInternal extends NotificationOptions {\n title: string;\n // Supported in the Legacy Send API.\n // See:https://firebase.google.com/docs/cloud-messaging/xmpp-server-ref.\n // eslint-disable-next-line camelcase\n click_action?: string;\n icon?: string;\n}\n\n// Defined in\n// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions. Note\n// that the keys are sent to the clients in snake cases which we need to convert to camel so it can\n// be exposed as a type to match the Firebase API convention.\nexport interface FcmOptionsInternal {\n link?: string;\n\n // eslint-disable-next-line camelcase\n analytics_label?: string;\n}\n\nexport enum MessageType {\n PUSH_RECEIVED = 'push-received',\n NOTIFICATION_CLICKED = 'notification-clicked'\n}\n\n/** Additional data of a message sent from the FN Console. */\nexport interface ConsoleMessageData {\n [CONSOLE_CAMPAIGN_ID]: string;\n [CONSOLE_CAMPAIGN_TIME]: string;\n [CONSOLE_CAMPAIGN_NAME]?: string;\n [CONSOLE_CAMPAIGN_ANALYTICS_ENABLED]?: '1';\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseFunctions, HttpsCallable } from '@firebase/functions-types';\nimport {\n httpsCallable as httpsCallableExp,\n httpsCallableFromURL as httpsCallableFromURLExp,\n connectFunctionsEmulator as useFunctionsEmulatorExp,\n HttpsCallableOptions,\n Functions as FunctionsServiceExp\n} from '@firebase/functions';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\nimport { FirebaseError } from '@firebase/util';\n\nexport class FunctionsService implements FirebaseFunctions, _FirebaseService {\n /**\n * For testing.\n * @internal\n */\n _region: string;\n /**\n * For testing.\n * @internal\n */\n _customDomain: string | null;\n\n constructor(\n public app: FirebaseApp,\n readonly _delegate: FunctionsServiceExp\n ) {\n this._region = this._delegate.region;\n this._customDomain = this._delegate.customDomain;\n }\n httpsCallable(name: string, options?: HttpsCallableOptions): HttpsCallable {\n return httpsCallableExp(this._delegate, name, options);\n }\n httpsCallableFromURL(\n url: string,\n options?: HttpsCallableOptions\n ): HttpsCallable {\n return httpsCallableFromURLExp(this._delegate, url, options);\n }\n /**\n * Deprecated in pre-modularized repo, does not exist in modularized\n * functions package, need to convert to \"host\" and \"port\" args that\n * `useFunctionsEmulatorExp` takes.\n * @deprecated\n */\n useFunctionsEmulator(origin: string): void {\n const match = origin.match('[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?');\n if (match == null) {\n throw new FirebaseError(\n 'functions',\n 'No origin provided to useFunctionsEmulator()'\n );\n }\n if (match[2] == null) {\n throw new FirebaseError(\n 'functions',\n 'Port missing in origin provided to useFunctionsEmulator()'\n );\n }\n return useFunctionsEmulatorExp(this._delegate, match[1], Number(match[2]));\n }\n useEmulator(host: string, port: number): void {\n return useFunctionsEmulatorExp(this._delegate, host, port);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase from '@firebase/app-compat';\nimport { name, version } from '../package.json';\nimport { registerFunctions } from './register';\nimport * as types from '@firebase/functions-types';\n\nregisterFunctions();\nfirebase.registerVersion(name, version);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n functions: {\n (app?: FirebaseApp): types.FirebaseFunctions;\n Functions: typeof types.FirebaseFunctions;\n };\n }\n interface FirebaseApp {\n functions(regionOrCustomDomain?: string): types.FirebaseFunctions;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function arrayToBase64(array: Uint8Array | ArrayBuffer): string {\n const uint8Array = new Uint8Array(array);\n const base64String = btoa(String.fromCharCode(...uint8Array));\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n\nexport function base64ToArray(base64String: string): Uint8Array {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\n const base64 = (base64String + padding)\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n\n const rawData = atob(base64);\n const outputArray = new Uint8Array(rawData.length);\n\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { deleteDB, openDB } from 'idb';\n\nimport { TokenDetails } from '../interfaces/token-details';\nimport { arrayToBase64 } from './array-base64-translator';\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, so that the upgrade\n * 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 and does not exist in all browsers. TODO: Remove\n // typecast when it lands in TS types.\n const databases = await (\n indexedDB as {\n databases(): Promise<Array<{ name: string; version: number }>>;\n }\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, {\n upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\n if (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 = upgradeTransaction.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 (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 (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 (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 });\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DBSchema, IDBPDatabase, deleteDB, openDB } from 'idb';\n\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { TokenDetails } from '../interfaces/token-details';\nimport { migrateOldDatabase } from '../helpers/migrate-old-database';\n\n// Exported for tests.\nexport const DATABASE_NAME = 'firebase-messaging-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\n\ninterface MessagingDB extends DBSchema {\n 'firebase-messaging-store': {\n key: string;\n value: TokenDetails;\n };\n}\n\nlet dbPromise: Promise<IDBPDatabase<MessagingDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<MessagingDB>> {\n if (!dbPromise) {\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n upgrade: (upgradeDb, oldVersion) => {\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\n // because if there are multiple versions between the old version and the current version, we\n // want ALL the migrations that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (oldVersion) {\n case 0:\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\n }\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)) as TokenDetails;\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.done;\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.done;\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 INDEXED_DB_UNSUPPORTED = 'indexed-db-unsupported',\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.INDEXED_DB_UNSUPPORTED]:\n \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\n [ErrorCode.FAILED_DEFAULT_REGISTRATION]:\n 'We are unable to register the default service worker. {$browserErrorMessage}',\n [ErrorCode.TOKEN_SUBSCRIBE_FAILED]:\n 'A problem occurred 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 occurred while unsubscribing the ' +\n 'user from FCM: {$errorInfo}',\n [ErrorCode.TOKEN_UPDATE_FAILED]:\n 'A problem occurred 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_VAPID_KEY, ENDPOINT } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { SubscriptionOptions, TokenDetails } from '../interfaces/token-details';\n\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\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 as Error)?.toString()\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 as Error)?.toString()\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 as Error)?.toString()\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SubscriptionOptions, TokenDetails } from '../interfaces/token-details';\nimport {\n arrayToBase64,\n base64ToArray\n} from '../helpers/array-base64-translator';\nimport { dbGet, dbRemove, dbSet } from './idb-manager';\nimport {\n requestDeleteToken,\n requestGetToken,\n requestUpdateToken\n} from './requests';\n\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { MessagingService } from '../messaging-service';\n\n// UpdateRegistration will be called once every week.\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport async function getTokenInternal(\n messaging: MessagingService\n): Promise<string> {\n const pushSubscription = await getPushSubscription(\n messaging.swRegistration!,\n messaging.vapidKey!\n );\n\n const subscriptionOptions: SubscriptionOptions = {\n vapidKey: messaging.vapidKey!,\n swScope: messaging.swRegistration!.scope,\n endpoint: pushSubscription.endpoint,\n auth: arrayToBase64(pushSubscription.getKey('auth')!),\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh')!)\n };\n\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\n if (!tokenDetails) {\n // No token, get a new one.\n return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\n } else if (\n !isTokenValid(tokenDetails.subscriptionOptions!, subscriptionOptions)\n ) {\n // Invalid token, get a new one.\n try {\n await requestDeleteToken(\n messaging.firebaseDependencies!,\n tokenDetails.token\n );\n } catch (e) {\n // Suppress errors because of #2364\n console.warn(e);\n }\n\n return getNewToken(messaging.firebaseDependencies!, subscriptionOptions);\n } else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\n // Weekly token refresh\n return updateToken(messaging, {\n token: tokenDetails.token,\n createTime: Date.now(),\n subscriptionOptions\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 FCM, and unregisters\n * the push subscription if it exists.\n */\nexport async function deleteTokenInternal(\n messaging: MessagingService\n): Promise<boolean> {\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\n if (tokenDetails) {\n await requestDeleteToken(\n messaging.firebaseDependencies,\n tokenDetails.token\n );\n await dbRemove(messaging.firebaseDependencies);\n }\n\n // Unsubscribe from the push subscription.\n const pushSubscription =\n await messaging.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 messaging: MessagingService,\n tokenDetails: TokenDetails\n): Promise<string> {\n try {\n const updatedToken = await requestUpdateToken(\n messaging.firebaseDependencies,\n tokenDetails\n );\n\n const updatedTokenDetails: TokenDetails = {\n ...tokenDetails,\n token: updatedToken,\n createTime: Date.now()\n };\n\n await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\n return updatedToken;\n } catch (e) {\n await deleteTokenInternal(messaging);\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\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\n // submitted to pushManager#subscribe must be of type Uint8Array.\n applicationServerKey: base64ToArray(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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MessagePayload } from '../interfaces/public-types';\nimport { MessagePayloadInternal } from '../interfaces/internal-message-payload';\n\nexport function externalizePayload(\n internalPayload: MessagePayloadInternal\n): MessagePayload {\n const payload: MessagePayload = {\n from: internalPayload.from,\n // eslint-disable-next-line camelcase\n collapseKey: internalPayload.collapse_key,\n // eslint-disable-next-line camelcase\n messageId: internalPayload.fcmMessageId\n } as MessagePayload;\n\n propagateNotificationPayload(payload, internalPayload);\n propagateDataPayload(payload, internalPayload);\n propagateFcmOptions(payload, internalPayload);\n\n return payload;\n}\n\nfunction propagateNotificationPayload(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n if (!messagePayloadInternal.notification) {\n return;\n }\n\n payload.notification = {};\n\n const title = messagePayloadInternal.notification!.title;\n if (!!title) {\n payload.notification!.title = title;\n }\n\n const body = messagePayloadInternal.notification!.body;\n if (!!body) {\n payload.notification!.body = body;\n }\n\n const image = messagePayloadInternal.notification!.image;\n if (!!image) {\n payload.notification!.image = image;\n }\n\n const icon = messagePayloadInternal.notification!.icon;\n if (!!icon) {\n payload.notification!.icon = icon;\n }\n}\n\nfunction propagateDataPayload(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n if (!messagePayloadInternal.data) {\n return;\n }\n\n payload.data = messagePayloadInternal.data as { [key: string]: string };\n}\n\nfunction propagateFcmOptions(\n payload: MessagePayload,\n messagePayloadInternal: MessagePayloadInternal\n): void {\n // fcmOptions.link value is written into notification.click_action. see more in b/232072111\n if (\n !messagePayloadInternal.fcmOptions &&\n !messagePayloadInternal.notification?.click_action\n ) {\n return;\n }\n\n payload.fcmOptions = {};\n\n const link =\n messagePayloadInternal.fcmOptions?.link ??\n messagePayloadInternal.notification?.click_action;\n\n if (!!link) {\n payload.fcmOptions!.link = link;\n }\n\n // eslint-disable-next-line camelcase\n const analyticsLabel = messagePayloadInternal.fcmOptions?.analytics_label;\n if (!!analyticsLabel) {\n payload.fcmOptions!.analyticsLabel = analyticsLabel;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_BACKOFF_TIME_MS,\n EVENT_MESSAGE_DELIVERED,\n FCM_LOG_SOURCE,\n LOG_INTERVAL_IN_MS,\n MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST,\n MAX_RETRIES,\n MessageType,\n SDK_PLATFORM_WEB\n} from '../util/constants';\nimport {\n FcmEvent,\n LogEvent,\n LogRequest,\n LogResponse,\n ComplianceData\n} from '../interfaces/logging-types';\n\nimport { MessagePayloadInternal } from '../interfaces/internal-message-payload';\nimport { MessagingService } from '../messaging-service';\n\nconst FIRELOG_ENDPOINT = _mergeStrings(\n 'hts/frbslgigp.ogepscmv/ieo/eaylg',\n 'tp:/ieaeogn-agolai.o/1frlglgc/o'\n);\n\nconst FCM_TRANSPORT_KEY = _mergeStrings(\n 'AzSCbw63g1R0nCw85jG8',\n 'Iaya3yLKwmgvh7cF0q4'\n);\n\nexport function startLoggingService(messaging: MessagingService): void {\n if (!messaging.isLogServiceStarted) {\n _processQueue(messaging, LOG_INTERVAL_IN_MS);\n messaging.isLogServiceStarted = true;\n }\n}\n\n/**\n *\n * @param messaging the messaging instance.\n * @param offsetInMs this method execute after `offsetInMs` elapsed .\n */\nexport function _processQueue(\n messaging: MessagingService,\n offsetInMs: number\n): void {\n setTimeout(async () => {\n if (!messaging.deliveryMetricsExportedToBigQueryEnabled) {\n // flush events and terminate logging service\n messaging.logEvents = [];\n messaging.isLogServiceStarted = false;\n\n return;\n }\n\n if (!messaging.logEvents.length) {\n return _processQueue(messaging, LOG_INTERVAL_IN_MS);\n }\n\n await _dispatchLogEvents(messaging);\n }, offsetInMs);\n}\n\nexport async function _dispatchLogEvents(\n messaging: MessagingService\n): Promise<void> {\n for (\n let i = 0, n = messaging.logEvents.length;\n i < n;\n i += MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST\n ) {\n const logRequest = _createLogRequest(\n messaging.logEvents.slice(i, i + MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST)\n );\n\n let retryCount = 0,\n response = {} as Response;\n\n do {\n try {\n response = await fetch(\n FIRELOG_ENDPOINT.concat('?key=', FCM_TRANSPORT_KEY),\n {\n method: 'POST',\n body: JSON.stringify(logRequest)\n }\n );\n\n // don't retry on 200s or non retriable errors\n if (response.ok || (!response.ok && !isRetriableError(response))) {\n break;\n }\n\n if (!response.ok && isRetriableError(response)) {\n // rethrow to retry with quota\n throw new Error(\n 'a retriable Non-200 code is returned in fetch to Firelog endpoint. Retry'\n );\n }\n } catch (error) {\n const isLastAttempt = retryCount === MAX_RETRIES;\n if (isLastAttempt) {\n // existing the do-while interactive retry logic because retry quota has reached.\n break;\n }\n }\n\n let delayInMs: number;\n try {\n delayInMs = Number(\n ((await response.json()) as LogResponse).nextRequestWaitMillis\n );\n } catch (e) {\n delayInMs = DEFAULT_BACKOFF_TIME_MS;\n }\n\n await new Promise(resolve => setTimeout(resolve, delayInMs));\n\n retryCount++;\n } while (retryCount < MAX_RETRIES);\n }\n\n messaging.logEvents = [];\n // schedule for next logging\n _processQueue(messaging, LOG_INTERVAL_IN_MS);\n}\n\nfunction isRetriableError(response: Response): boolean {\n const httpStatus = response.status;\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\nexport async function stageLog(\n messaging: MessagingService,\n internalPayload: MessagePayloadInternal\n): Promise<void> {\n const fcmEvent = createFcmEvent(\n internalPayload,\n await messaging.firebaseDependencies.installations.getId()\n );\n\n createAndEnqueueLogEvent(messaging, fcmEvent, internalPayload.productId);\n}\n\nfunction createFcmEvent(\n internalPayload: MessagePayloadInternal,\n fid: string\n): FcmEvent {\n const fcmEvent = {} as FcmEvent;\n\n /* eslint-disable camelcase */\n // some fields should always be non-null. Still check to ensure.\n if (!!internalPayload.from) {\n fcmEvent.project_number = internalPayload.from;\n }\n\n if (!!internalPayload.fcmMessageId) {\n fcmEvent.message_id = internalPayload.fcmMessageId;\n }\n\n fcmEvent.instance_id = fid;\n\n if (!!internalPayload.notification) {\n fcmEvent.message_type = MessageType.DISPLAY_NOTIFICATION.toString();\n } else {\n fcmEvent.message_type = MessageType.DATA_MESSAGE.toString();\n }\n\n fcmEvent.sdk_platform = SDK_PLATFORM_WEB.toString();\n fcmEvent.package_name = self.origin.replace(/(^\\w+:|^)\\/\\//, '');\n\n if (!!internalPayload.collapse_key) {\n fcmEvent.collapse_key = internalPayload.collapse_key;\n }\n\n fcmEvent.event = EVENT_MESSAGE_DELIVERED.toString();\n\n if (!!internalPayload.fcmOptions?.analytics_label) {\n fcmEvent.analytics_label = internalPayload.fcmOptions?.analytics_label;\n }\n\n /* eslint-enable camelcase */\n return fcmEvent;\n}\n\nfunction createAndEnqueueLogEvent(\n messaging: MessagingService,\n fcmEvent: FcmEvent,\n productId: number\n): void {\n const logEvent = {} as LogEvent;\n\n /* eslint-disable camelcase */\n logEvent.event_time_ms = Math.floor(Date.now()).toString();\n logEvent.source_extension_json_proto3 = JSON.stringify(fcmEvent);\n\n if (!!productId) {\n logEvent.compliance_data = buildComplianceData(productId);\n }\n // eslint-disable-next-line camelcase\n\n messaging.logEvents.push(logEvent);\n}\n\nfunction buildComplianceData(productId: number): ComplianceData {\n const complianceData: ComplianceData = {\n privacy_context: {\n prequest: {\n origin_associated_product_id: productId\n }\n }\n };\n\n return complianceData;\n}\n\nexport function _createLogRequest(logEventQueue: LogEvent[]): LogRequest {\n const logRequest = {} as LogRequest;\n\n /* eslint-disable camelcase */\n logRequest.log_source = FCM_LOG_SOURCE.toString();\n logRequest.log_event = logEventQueue;\n /* eslint-enable camelcase */\n\n return logRequest;\n}\n\nexport function _mergeStrings(s1: string, s2: string): string {\n const resultArray = [];\n for (let i = 0; i < s1.length; i++) {\n resultArray.push(s1.charAt(i));\n if (i < s2.length) {\n resultArray.push(s2.charAt(i));\n }\n }\n\n return resultArray.join('');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\n\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseError } from '@firebase/util';\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { MessagePayload, NextFn, Observer } from './interfaces/public-types';\n\nimport { FirebaseAnalyticsInternalName } from '@firebase/analytics-interop-types';\nimport { FirebaseInternalDependencies } from './interfaces/internal-dependencies';\nimport { LogEvent } from './interfaces/logging-types';\nimport { Provider } from '@firebase/component';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { extractAppConfig } from './helpers/extract-app-config';\n\nexport class MessagingService implements _FirebaseService {\n readonly app!: FirebaseApp;\n readonly firebaseDependencies!: FirebaseInternalDependencies;\n\n swRegistration?: ServiceWorkerRegistration;\n vapidKey?: string;\n // logging is only done with end user consent. Default to false.\n deliveryMetricsExportedToBigQueryEnabled: boolean = false;\n\n onBackgroundMessageHandler:\n | NextFn<MessagePayload>\n | Observer<MessagePayload>\n | null = null;\n\n onMessageHandler: NextFn<MessagePayload> | Observer<MessagePayload> | null =\n null;\n\n logEvents: LogEvent[] = [];\n isLogServiceStarted: boolean = false;\n\n constructor(\n app: FirebaseApp,\n installations: _FirebaseInstallationsInternal,\n analyticsProvider: Provider<FirebaseAnalyticsInternalName>\n ) {\n const appConfig = extractAppConfig(app);\n\n this.firebaseDependencies = {\n app,\n appConfig,\n installations,\n analyticsProvider\n };\n }\n\n _delete(): Promise<void> {\n return Promise.resolve();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_SW_PATH, DEFAULT_SW_SCOPE } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\n\nexport async function registerDefaultSw(\n messaging: MessagingService\n): Promise<void> {\n try {\n messaging.swRegistration = await navigator.serviceWorker.register(\n DEFAULT_SW_PATH,\n {\n scope: DEFAULT_SW_SCOPE\n }\n );\n\n // The timing when browser updates sw when sw has an update is unreliable from experiment. It\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\n // is stuck with the old version. For example,\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\n // sw if there was an update.\n messaging.swRegistration.update().catch(() => {\n /* it is non blocking and we don't care if it failed */\n });\n } catch (e) {\n throw ERROR_FACTORY.create(ErrorCode.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: (e as Error)?.message\n });\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { getTokenInternal } from '../internals/token-manager';\nimport { updateSwReg } from '../helpers/updateSwReg';\nimport { updateVapidKey } from '../helpers/updateVapidKey';\nimport { GetTokenOptions } from '../interfaces/public-types';\n\nexport async function getToken(\n messaging: MessagingService,\n options?: GetTokenOptions\n): Promise<string> {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n if (Notification.permission === 'default') {\n await Notification.requestPermission();\n }\n\n if (Notification.permission !== 'granted') {\n throw ERROR_FACTORY.create(ErrorCode.PERMISSION_BLOCKED);\n }\n\n await updateVapidKey(messaging, options?.vapidKey);\n await updateSwReg(messaging, options?.serviceWorkerRegistration);\n\n return getTokenInternal(messaging);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_VAPID_KEY } from '../util/constants';\nimport { MessagingService } from '../messaging-service';\n\nexport async function updateVapidKey(\n messaging: MessagingService,\n vapidKey?: string | undefined\n): Promise<void> {\n if (!!vapidKey) {\n messaging.vapidKey = vapidKey;\n } else if (!messaging.vapidKey) {\n messaging.vapidKey = DEFAULT_VAPID_KEY;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { registerDefaultSw } from './registerDefaultSw';\n\nexport async function updateSwReg(\n messaging: MessagingService,\n swRegistration?: ServiceWorkerRegistration | undefined\n): Promise<void> {\n if (!swRegistration && !messaging.swRegistration) {\n await registerDefaultSw(messaging);\n }\n\n if (!swRegistration && !!messaging.swRegistration) {\n return;\n }\n\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_SW_REGISTRATION);\n }\n\n messaging.swRegistration = swRegistration;\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CONSOLE_CAMPAIGN_ID,\n CONSOLE_CAMPAIGN_NAME,\n CONSOLE_CAMPAIGN_TIME\n} from '../util/constants';\nimport {\n ConsoleMessageData,\n MessageType\n} from '../interfaces/internal-message-payload';\n\nimport { MessagingService } from '../messaging-service';\n\nexport async function logToScion(\n messaging: MessagingService,\n messageType: MessageType,\n data: ConsoleMessageData\n): Promise<void> {\n const eventType = getEventType(messageType);\n const analytics =\n await messaging.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\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n MessagePayloadInternal,\n MessageType\n} from '../interfaces/internal-message-payload';\n\nimport { CONSOLE_CAMPAIGN_ANALYTICS_ENABLED } from '../util/constants';\nimport { MessagingService } from '../messaging-service';\nimport { externalizePayload } from '../helpers/externalizePayload';\nimport { isConsoleMessage } from '../helpers/is-console-message';\nimport { logToScion } from '../helpers/logToScion';\n\nexport async function messageEventListener(\n messaging: MessagingService,\n event: MessageEvent\n): Promise<void> {\n const internalPayload = event.data as MessagePayloadInternal;\n\n if (!internalPayload.isFirebaseMessaging) {\n return;\n }\n\n if (\n messaging.onMessageHandler &&\n internalPayload.messageType === MessageType.PUSH_RECEIVED\n ) {\n if (typeof messaging.onMessageHandler === 'function') {\n messaging.onMessageHandler(externalizePayload(internalPayload));\n } else {\n messaging.onMessageHandler.next(externalizePayload(internalPayload));\n }\n }\n\n // Log to Scion if applicable\n const dataPayload = internalPayload.data;\n if (\n isConsoleMessage(dataPayload) &&\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1'\n ) {\n await logToScion(messaging, internalPayload.messageType!, dataPayload);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSOLE_CAMPAIGN_ID } from '../util/constants';\nimport { ConsoleMessageData } from '../interfaces/internal-message-payload';\n\nexport function isConsoleMessage(data: unknown): data is ConsoleMessageData {\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport {\n onNotificationClick,\n onPush,\n onSubChange\n} from '../listeners/sw-listeners';\n\nimport { GetTokenOptions } from '../interfaces/public-types';\nimport { MessagingInternal } from '@firebase/messaging-interop-types';\nimport { MessagingService } from '../messaging-service';\nimport { ServiceWorkerGlobalScope } from '../util/sw-types';\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport { getToken } from '../api/getToken';\nimport { messageEventListener } from '../listeners/window-listener';\n\nimport { name, version } from '../../package.json';\n\nconst WindowMessagingFactory: InstanceFactory<'messaging'> = (\n container: ComponentContainer\n) => {\n const messaging = new MessagingService(\n container.getProvider('app').getImmediate(),\n container.getProvider('installations-internal').getImmediate(),\n container.getProvider('analytics-internal')\n );\n\n navigator.serviceWorker.addEventListener('message', e =>\n messageEventListener(messaging as MessagingService, e)\n );\n\n return messaging;\n};\n\nconst WindowMessagingInternalFactory: InstanceFactory<'messaging-internal'> = (\n container: ComponentContainer\n) => {\n const messaging = container\n .getProvider('messaging')\n .getImmediate() as MessagingService;\n\n const messagingInternal: MessagingInternal = {\n getToken: (options?: GetTokenOptions) => getToken(messaging, options)\n };\n\n return messagingInternal;\n};\n\ndeclare const self: ServiceWorkerGlobalScope;\nconst SwMessagingFactory: InstanceFactory<'messaging'> = (\n container: ComponentContainer\n) => {\n const messaging = new MessagingService(\n container.getProvider('app').getImmediate(),\n container.getProvider('installations-internal').getImmediate(),\n container.getProvider('analytics-internal')\n );\n\n self.addEventListener('push', e => {\n e.waitUntil(onPush(e, messaging as MessagingService));\n });\n self.addEventListener('pushsubscriptionchange', e => {\n e.waitUntil(onSubChange(e, messaging as MessagingService));\n });\n self.addEventListener('notificationclick', e => {\n e.waitUntil(onNotificationClick(e));\n });\n\n return messaging;\n};\n\nexport function registerMessagingInWindow(): void {\n _registerComponent(\n new Component('messaging', WindowMessagingFactory, ComponentType.PUBLIC)\n );\n\n _registerComponent(\n new Component(\n 'messaging-internal',\n WindowMessagingInternalFactory,\n ComponentType.PRIVATE\n )\n );\n\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\n/**\n * The messaging instance registered in sw is named differently than that of in client. This is\n * because both `registerMessagingInWindow` and `registerMessagingInSw` would be called in\n * `messaging-compat` and component with the same name can only be registered once.\n */\nexport function registerMessagingInSw(): void {\n _registerComponent(\n new Component('messaging-sw', SwMessagingFactory, ComponentType.PUBLIC)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from './util/errors';\nimport { FirebaseApp, _getProvider, getApp } from '@firebase/app';\nimport {\n GetTokenOptions,\n MessagePayload,\n Messaging\n} from './interfaces/public-types';\nimport {\n NextFn,\n Observer,\n Unsubscribe,\n getModularInstance\n} from '@firebase/util';\nimport { isSwSupported, isWindowSupported } from './api/isSupported';\n\nimport { MessagingService } from './messaging-service';\nimport { deleteToken as _deleteToken } from './api/deleteToken';\nimport { getToken as _getToken } from './api/getToken';\nimport { onBackgroundMessage as _onBackgroundMessage } from './api/onBackgroundMessage';\nimport { onMessage as _onMessage } from './api/onMessage';\nimport { _setDeliveryMetricsExportedToBigQueryEnabled } from './api/setDeliveryMetricsExportedToBigQueryEnabled';\n\n/**\n * Retrieves a Firebase Cloud Messaging instance.\n *\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\n *\n * @public\n */\nexport function getMessagingInWindow(app: FirebaseApp = getApp()): Messaging {\n // Conscious decision to make this async check non-blocking during the messaging instance\n // initialization phase for performance consideration. An error would be thrown latter for\n // developer's information. Developers can then choose to import and call `isSupported` for\n // special handling.\n isWindowSupported().then(\n isSupported => {\n // If `isWindowSupported()` resolved, but returned false.\n if (!isSupported) {\n throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n }\n },\n _ => {\n // If `isWindowSupported()` rejected.\n throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);\n }\n );\n return _getProvider(getModularInstance(app), 'messaging').getImmediate();\n}\n\n/**\n * Retrieves a Firebase Cloud Messaging instance.\n *\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\n *\n * @public\n */\nexport function getMessagingInSw(app: FirebaseApp = getApp()): Messaging {\n // Conscious decision to make this async check non-blocking during the messaging instance\n // initialization phase for performance consideration. An error would be thrown latter for\n // developer's information. Developers can then choose to import and call `isSupported` for\n // special handling.\n isSwSupported().then(\n isSupported => {\n // If `isSwSupported()` resolved, but returned false.\n if (!isSupported) {\n throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n }\n },\n _ => {\n // If `isSwSupported()` rejected.\n throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);\n }\n );\n return _getProvider(getModularInstance(app), 'messaging-sw').getImmediate();\n}\n\n/**\n * Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\n * instance.\n *\n * If notification permission isn't already granted, this method asks the user for permission. The\n * returned promise rejects if the user does not allow the app to show notifications.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param options - Provides an optional vapid key and an optional service worker registration.\n *\n * @returns The promise resolves with an FCM registration token.\n *\n * @public\n */\nexport async function getToken(\n messaging: Messaging,\n options?: GetTokenOptions\n): Promise<string> {\n messaging = getModularInstance(messaging);\n return _getToken(messaging as MessagingService, options);\n}\n\n/**\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\n * the {@link Messaging} instance from the push subscription.\n *\n * @param messaging - The {@link Messaging} instance.\n *\n * @returns The promise resolves when the token has been successfully deleted.\n *\n * @public\n */\nexport function deleteToken(messaging: Messaging): Promise<boolean> {\n messaging = getModularInstance(messaging);\n return _deleteToken(messaging as MessagingService);\n}\n\n/**\n * When a push message is received and the user is currently on a page for your origin, the\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\n * the push message.\n *\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - This function, or observer object with `next` defined,\n * is called when a message is received and the user is currently viewing your page.\n * @returns To stop listening for messages execute this returned function.\n *\n * @public\n */\nexport function onMessage(\n messaging: Messaging,\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n messaging = getModularInstance(messaging);\n return _onMessage(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Called when a message is received while the app is in the background. An app is considered to be\n * in the background if no active window is displayed.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - This function, or observer object with `next` defined, is called when a\n * message is received and the app is currently in the background.\n *\n * @returns To stop listening for messages execute this returned function\n *\n * @public\n */\nexport function onBackgroundMessage(\n messaging: Messaging,\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n messaging = getModularInstance(messaging);\n return _onBackgroundMessage(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Enables or disables Firebase Cloud Messaging message delivery metrics export to BigQuery. By\n * default, message delivery metrics are not exported to BigQuery. Use this method to enable or\n * disable the export at runtime.\n *\n * @param messaging - The `FirebaseMessaging` instance.\n * @param enable - Whether Firebase Cloud Messaging should export message delivery metrics to\n * BigQuery.\n *\n * @public\n */\nexport function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(\n messaging: Messaging,\n enable: boolean\n): void {\n messaging = getModularInstance(messaging);\n return _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { deleteTokenInternal } from '../internals/token-manager';\nimport { registerDefaultSw } from '../helpers/registerDefaultSw';\n\nexport async function deleteToken(\n messaging: MessagingService\n): Promise<boolean> {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n if (!messaging.swRegistration) {\n await registerDefaultSw(messaging);\n }\n\n return deleteTokenInternal(messaging);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport {\n MessagePayload,\n NextFn,\n Observer,\n Unsubscribe\n} from '../interfaces/public-types';\nimport { MessagingService } from '../messaging-service';\n\nexport function onMessage(\n messaging: MessagingService,\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n if (!navigator) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n messaging.onMessageHandler = nextOrObserver;\n\n return () => {\n messaging.onMessageHandler = null;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_VAPID_KEY, FCM_MSG } from '../util/constants';\nimport {\n MessagePayloadInternal,\n MessageType,\n NotificationPayloadInternal\n} from '../interfaces/internal-message-payload';\nimport {\n NotificationEvent,\n PushEvent,\n PushSubscriptionChangeEvent,\n ServiceWorkerGlobalScope,\n WindowClient\n} from '../util/sw-types';\nimport {\n deleteTokenInternal,\n getTokenInternal\n} from '../internals/token-manager';\n\nimport { MessagingService } from '../messaging-service';\nimport { dbGet } from '../internals/idb-manager';\nimport { externalizePayload } from '../helpers/externalizePayload';\nimport { isConsoleMessage } from '../helpers/is-console-message';\nimport { sleep } from '../helpers/sleep';\nimport { stageLog } from '../helpers/logToFirelog';\n\n// maxActions is an experimental property and not part of the official\n// TypeScript interface\n// https://developer.mozilla.org/en-US/docs/Web/API/Notification/maxActions\ninterface NotificationExperimental extends Notification {\n maxActions?: number;\n}\n\n// Let TS know that this is a service worker\ndeclare const self: ServiceWorkerGlobalScope;\n\nexport async function onSubChange(\n event: PushSubscriptionChangeEvent,\n messaging: MessagingService\n): Promise<void> {\n const { newSubscription } = event;\n if (!newSubscription) {\n // Subscription revoked, delete token\n await deleteTokenInternal(messaging);\n return;\n }\n\n const tokenDetails = await dbGet(messaging.firebaseDependencies);\n await deleteTokenInternal(messaging);\n\n messaging.vapidKey =\n tokenDetails?.subscriptionOptions?.vapidKey ?? DEFAULT_VAPID_KEY;\n await getTokenInternal(messaging);\n}\n\nexport async function onPush(\n event: PushEvent,\n messaging: MessagingService\n): Promise<void> {\n const internalPayload = getMessagePayloadInternal(event);\n if (!internalPayload) {\n // Failed to get parsed MessagePayload from the PushEvent. Skip handling the push.\n return;\n }\n\n // log to Firelog with user consent\n if (messaging.deliveryMetricsExportedToBigQueryEnabled) {\n await stageLog(messaging, internalPayload);\n }\n\n // foreground handling: eventually passed to onMessage hook\n const clientList = await getClientList();\n if (hasVisibleClients(clientList)) {\n return sendMessagePayloadInternalToWindows(clientList, internalPayload);\n }\n\n // background handling: display if possible and pass to onBackgroundMessage hook\n if (!!internalPayload.notification) {\n await showNotification(wrapInternalPayload(internalPayload));\n }\n\n if (!messaging) {\n return;\n }\n\n if (!!messaging.onBackgroundMessageHandler) {\n const payload = externalizePayload(internalPayload);\n\n if (typeof messaging.onBackgroundMessageHandler === 'function') {\n await messaging.onBackgroundMessageHandler(payload);\n } else {\n messaging.onBackgroundMessageHandler.next(payload);\n }\n }\n}\n\nexport async function onNotificationClick(\n event: NotificationEvent\n): Promise<void> {\n const internalPayload: MessagePayloadInternal =\n event.notification?.data?.[FCM_MSG];\n\n if (!internalPayload) {\n return;\n } else if (event.action) {\n // User clicked on an action button. This will allow developers to act on action button clicks\n // by using a custom 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 // Note clicking on a notification with no link set will focus the Chrome's current tab.\n const link = getLink(internalPayload);\n if (!link) {\n return;\n }\n\n // FM should only open/focus links from app's origin.\n const url = new URL(link, self.location.href);\n const originUrl = new URL(self.location.origin);\n\n if (url.host !== originUrl.host) {\n return;\n }\n\n let client = await getWindowClient(url);\n\n if (!client) {\n client = await self.clients.openWindow(link);\n\n // Wait three seconds for the client to initialize and set up the message handler so that it\n // 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 internalPayload.messageType = MessageType.NOTIFICATION_CLICKED;\n internalPayload.isFirebaseMessaging = true;\n return client.postMessage(internalPayload);\n}\n\nfunction wrapInternalPayload(\n internalPayload: MessagePayloadInternal\n): NotificationPayloadInternal {\n const wrappedInternalPayload: NotificationPayloadInternal = {\n ...(internalPayload.notification as unknown as NotificationPayloadInternal)\n };\n\n // Put the message payload under FCM_MSG name so we can identify the notification as being an FCM\n // notification vs a notification from somewhere else (i.e. normal web push or developer generated\n // notification).\n wrappedInternalPayload.data = {\n [FCM_MSG]: internalPayload\n };\n\n return wrappedInternalPayload;\n}\n\nfunction getMessagePayloadInternal({\n data\n}: PushEvent): MessagePayloadInternal | 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\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: URL): Promise<WindowClient | null> {\n const clientList = await getClientList();\n\n for (const client of clientList) {\n const clientUrl = new URL(client.url, self.location.href);\n\n if (url.host === clientUrl.host) {\n return client;\n }\n }\n\n return null;\n}\n\n/**\n * @returns If there is currently a visible WindowClient, this method will resolve to true,\n * 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 of extensions, which\n // are always considered visible for some reason.\n !client.url.startsWith('chrome-extension://')\n );\n}\n\nfunction sendMessagePayloadInternalToWindows(\n clientList: WindowClient[],\n internalPayload: MessagePayloadInternal\n): void {\n internalPayload.isFirebaseMessaging = true;\n internalPayload.messageType = MessageType.PUSH_RECEIVED;\n\n for (const client of clientList) {\n client.postMessage(internalPayload);\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 showNotification(\n notificationPayloadInternal: NotificationPayloadInternal\n): Promise<void> {\n // Note: Firefox does not support the maxActions property.\n // https://developer.mozilla.org/en-US/docs/Web/API/notification/maxActions\n const { actions } = notificationPayloadInternal;\n const { maxActions } = Notification as unknown as NotificationExperimental;\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(\n /* title= */ notificationPayloadInternal.title ?? '',\n notificationPayloadInternal\n );\n}\n\nfunction getLink(payload: MessagePayloadInternal): 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Returns a 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport {\n MessagePayload,\n NextFn,\n Observer,\n Unsubscribe\n} from '../interfaces/public-types';\nimport { MessagingService } from '../messaging-service';\n\nexport function onBackgroundMessage(\n messaging: MessagingService,\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n if (self.document !== undefined) {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_SW);\n }\n\n messaging.onBackgroundMessageHandler = nextOrObserver;\n\n return () => {\n messaging.onBackgroundMessageHandler = null;\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { CONFIG_STORAGE_BUCKET_KEY } from './constants';\n\n/**\n * An error returned by the Firebase Storage SDK.\n * @public\n */\nexport class StorageError extends FirebaseError {\n private readonly _baseMessage: string;\n /**\n * Stores custom error data unique to the `StorageError`.\n */\n customData: { serverResponse: string | null } = { serverResponse: null };\n\n /**\n * @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and\n * added to the end of the message.\n * @param message - Error message.\n * @param status_ - Corresponding HTTP Status Code\n */\n constructor(code: StorageErrorCode, message: string, private status_ = 0) {\n super(\n prependCode(code),\n `Firebase Storage: ${message} (${prependCode(code)})`\n );\n this._baseMessage = this.message;\n // Without this, `instanceof StorageError`, in tests for example,\n // returns false.\n Object.setPrototypeOf(this, StorageError.prototype);\n }\n\n get status(): number {\n return this.status_;\n }\n\n set status(status: number) {\n this.status_ = status;\n }\n\n /**\n * Compares a `StorageErrorCode` against this error's code, filtering out the prefix.\n */\n _codeEquals(code: StorageErrorCode): boolean {\n return prependCode(code) === this.code;\n }\n\n /**\n * Optional response message that was added by the server.\n */\n get serverResponse(): null | string {\n return this.customData.serverResponse;\n }\n\n set serverResponse(serverResponse: string | null) {\n this.customData.serverResponse = serverResponse;\n if (this.customData.serverResponse) {\n this.message = `${this._baseMessage}\\n${this.customData.serverResponse}`;\n } else {\n this.message = this._baseMessage;\n }\n }\n}\n\nexport const errors = {};\n\n/**\n * @public\n * Error codes that can be attached to `StorageError` objects.\n */\nexport enum StorageErrorCode {\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 UNAUTHORIZED_APP = 'unauthorized-app',\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 UNSUPPORTED_ENVIRONMENT = 'unsupported-environment'\n}\n\nexport function prependCode(code: StorageErrorCode): string {\n return 'storage/' + code;\n}\n\nexport function unknown(): StorageError {\n const message =\n 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new StorageError(StorageErrorCode.UNKNOWN, message);\n}\n\nexport function objectNotFound(path: string): StorageError {\n return new StorageError(\n StorageErrorCode.OBJECT_NOT_FOUND,\n \"Object '\" + path + \"' does not exist.\"\n );\n}\n\nexport function bucketNotFound(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.BUCKET_NOT_FOUND,\n \"Bucket '\" + bucket + \"' does not exist.\"\n );\n}\n\nexport function projectNotFound(project: string): StorageError {\n return new StorageError(\n StorageErrorCode.PROJECT_NOT_FOUND,\n \"Project '\" + project + \"' does not exist.\"\n );\n}\n\nexport function quotaExceeded(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.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(): StorageError {\n const message =\n 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new StorageError(StorageErrorCode.UNAUTHENTICATED, message);\n}\n\nexport function unauthorizedApp(): StorageError {\n return new StorageError(\n StorageErrorCode.UNAUTHORIZED_APP,\n 'This app does not have permission to access Firebase Storage on this project.'\n );\n}\n\nexport function unauthorized(path: string): StorageError {\n return new StorageError(\n StorageErrorCode.UNAUTHORIZED,\n \"User does not have permission to access '\" + path + \"'.\"\n );\n}\n\nexport function retryLimitExceeded(): StorageError {\n return new StorageError(\n StorageErrorCode.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): StorageError {\n return new StorageError(\n StorageErrorCode.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(): StorageError {\n return new StorageError(\n StorageErrorCode.CANCELED,\n 'User canceled the upload/download.'\n );\n}\n\nexport function invalidEventName(name: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_EVENT_NAME,\n \"Invalid event name '\" + name + \"'.\"\n );\n}\n\nexport function invalidUrl(url: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_URL,\n \"Invalid URL '\" + url + \"'.\"\n );\n}\n\nexport function invalidDefaultBucket(bucket: string): StorageError {\n return new StorageError(\n StorageErrorCode.INVALID_DEFAULT_BUCKET,\n \"Invalid default bucket '\" + bucket + \"'.\"\n );\n}\n\nexport function noDefaultBucket(): StorageError {\n return new StorageError(\n StorageErrorCode.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(): StorageError {\n return new StorageError(\n StorageErrorCode.CANNOT_SLICE_BLOB,\n 'Cannot slice blob for upload. Please retry the upload.'\n );\n}\n\nexport function serverFileWrongSize(): StorageError {\n return new StorageError(\n StorageErrorCode.SERVER_FILE_WRONG_SIZE,\n 'Server recorded incorrect upload file size, please retry the upload.'\n );\n}\n\nexport function noDownloadURL(): StorageError {\n return new StorageError(\n StorageErrorCode.NO_DOWNLOAD_URL,\n 'The given file does not have any download URLs.'\n );\n}\n\nexport function missingPolyFill(polyFill: string): StorageError {\n return new StorageError(\n StorageErrorCode.UNSUPPORTED_ENVIRONMENT,\n `${polyFill} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`\n );\n}\n\n/**\n * @internal\n */\nexport function invalidArgument(message: string): StorageError {\n return new StorageError(StorageErrorCode.INVALID_ARGUMENT, message);\n}\n\nexport function invalidArgumentCount(\n argMin: number,\n argMax: number,\n fnName: string,\n real: number\n): StorageError {\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 StorageError(\n StorageErrorCode.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(): StorageError {\n return new StorageError(\n StorageErrorCode.APP_DELETED,\n 'The Firebase app was deleted.'\n );\n}\n\n/**\n * @param name - The name of the operation that was invalid.\n *\n * @internal\n */\nexport function invalidRootOperation(name: string): StorageError {\n return new StorageError(\n StorageErrorCode.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(format: string, message: string): StorageError {\n return new StorageError(\n StorageErrorCode.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 unsupportedEnvironment(message: string): StorageError {\n throw new StorageError(StorageErrorCode.UNSUPPORTED_ENVIRONMENT, message);\n}\n\n/**\n * @param message - A message describing the internal error.\n */\nexport function internalError(message: string): StorageError {\n throw new StorageError(\n StorageErrorCode.INTERNAL_ERROR,\n 'Internal error: ' + message\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Network headers */\nexport type Headers = Record<string, string>;\n\n/** Response type exposed by the networking APIs. */\nexport type ConnectionType =\n | string\n | ArrayBuffer\n | Blob\n | NodeJS.ReadableStream;\n\n/**\n * A lightweight wrapper around XMLHttpRequest with a\n * goog.net.XhrIo-like interface.\n *\n * You can create a new connection by invoking `newTextConnection()`,\n * `newBytesConnection()` or `newStreamConnection()`.\n */\nexport interface Connection<T extends ConnectionType> {\n /**\n * Sends a request to the provided URL.\n *\n * This method never rejects its promise. In case of encountering an error,\n * it sets an error code internally which can be accessed by calling\n * getErrorCode() by callers.\n */\n send(\n url: string,\n method: string,\n body?: ArrayBufferView | Blob | string | null,\n headers?: Headers\n ): Promise<void>;\n\n getErrorCode(): ErrorCode;\n\n getStatus(): number;\n\n getResponse(): T;\n\n getErrorText(): 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 * Error codes for requests made by the the XhrIo wrapper.\n */\nexport enum ErrorCode {\n NO_ERROR = 0,\n NETWORK_ERROR = 1,\n ABORT = 2\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app-compat';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport {\n StringFormat,\n _TaskEvent as TaskEvent,\n _TaskState as TaskState\n} from '@firebase/storage';\n\nimport { ReferenceCompat } from './reference';\nimport { StorageServiceCompat } from './service';\nimport * as types from '@firebase/storage-types';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\n/**\n * Type constant for Firebase Storage.\n */\nconst STORAGE_TYPE = 'storage-compat';\n\nfunction factory(\n container: ComponentContainer,\n { instanceIdentifier: url }: InstanceFactoryOptions\n): types.FirebaseStorage {\n // Dependencies\n const app = container.getProvider('app-compat').getImmediate();\n const storageExp = container\n .getProvider('storage')\n .getImmediate({ identifier: url });\n\n const storageServiceCompat: StorageServiceCompat = new StorageServiceCompat(\n app,\n storageExp\n );\n return storageServiceCompat;\n}\n\nexport function registerStorage(instance: _FirebaseNamespace): void {\n const namespaceExports = {\n // no-inline\n TaskState,\n TaskEvent,\n StringFormat,\n Storage: StorageServiceCompat,\n Reference: ReferenceCompat\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 unknown as _FirebaseNamespace);\n\n/**\n * Define extension behavior for `registerStorage`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n storage?: {\n (app?: FirebaseApp, url?: string): 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp as AppCompat,\n _FirebaseService\n} from '@firebase/app-compat';\nimport {\n Messaging,\n MessagePayload,\n deleteToken,\n getToken,\n onMessage\n} from '@firebase/messaging';\nimport {\n areCookiesEnabled,\n isIndexedDBAvailable,\n NextFn,\n Observer,\n Unsubscribe\n} from '@firebase/util';\n\nimport { onBackgroundMessage } from '@firebase/messaging/sw';\n\nexport interface MessagingCompat {\n getToken(options?: {\n vapidKey?: string;\n serviceWorkerRegistration?: ServiceWorkerRegistration;\n }): Promise<string>;\n\n deleteToken(): Promise<boolean>;\n\n onMessage(\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n ): Unsubscribe;\n\n onBackgroundMessage(\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n ): Unsubscribe;\n}\n\nexport function isSupported(): boolean {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n // Running in ServiceWorker context\n return isSwSupported();\n } else {\n // Assume we are in the window context.\n return isWindowSupported();\n }\n}\n\n/**\n * Checks to see if the required APIs exist.\n * Unlike the modular version, it does not check if IndexedDB.open() is allowed\n * in order to keep isSupported() synchronous and maintain v8 compatibility.\n */\nfunction isWindowSupported(): boolean {\n return (\n typeof window !== 'undefined' &&\n isIndexedDBAvailable() &&\n areCookiesEnabled() &&\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 isSwSupported(): boolean {\n return (\n isIndexedDBAvailable() &&\n 'PushManager' in self &&\n 'Notification' in self &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n}\n\nexport class MessagingCompatImpl implements MessagingCompat, _FirebaseService {\n constructor(readonly app: AppCompat, readonly _delegate: Messaging) {\n this.app = app;\n this._delegate = _delegate;\n }\n\n async getToken(options?: {\n vapidKey?: string;\n serviceWorkerRegistration?: ServiceWorkerRegistration;\n }): Promise<string> {\n return getToken(this._delegate, options);\n }\n\n async deleteToken(): Promise<boolean> {\n return deleteToken(this._delegate);\n }\n\n onMessage(\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n ): Unsubscribe {\n return onMessage(this._delegate, nextOrObserver);\n }\n\n onBackgroundMessage(\n nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n ): Unsubscribe {\n return onBackgroundMessage(this._delegate, nextOrObserver);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactory\n} from '@firebase/component';\nimport { MessagingCompatImpl, isSupported } from './messaging-compat';\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'messaging-compat': MessagingCompatImpl;\n }\n}\n\nconst messagingCompatFactory: InstanceFactory<'messaging-compat'> = (\n container: ComponentContainer\n) => {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n // in sw\n return new MessagingCompatImpl(\n container.getProvider('app-compat').getImmediate(),\n container.getProvider('messaging-sw').getImmediate()\n );\n } else {\n // in window\n return new MessagingCompatImpl(\n container.getProvider('app-compat').getImmediate(),\n container.getProvider('messaging').getImmediate()\n );\n }\n};\n\nconst NAMESPACE_EXPORTS = {\n isSupported\n};\n\nexport function registerMessagingCompat(): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'messaging-compat',\n messagingCompatFactory,\n ComponentType.PUBLIC\n ).setServiceProps(NAMESPACE_EXPORTS)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { name, version } from '../package.json';\n\nimport firebase from '@firebase/app-compat';\nimport { registerMessagingCompat } from './registerMessagingCompat';\nimport { MessagingCompat } from './messaging-compat';\n\nregisterMessagingCompat();\nfirebase.registerVersion(name, version);\n\n/**\n * Define extension behavior of `registerMessaging`\n */\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n messaging: {\n (app?: FirebaseApp): MessagingCompat;\n isSupported(): boolean;\n };\n }\n interface FirebaseApp {\n messaging(): MessagingCompat;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @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 * 1 second\n */\nexport const DEFAULT_MIN_SLEEP_TIME_MILLIS = 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\n\nimport { invalidDefaultBucket, invalidUrl } from './error';\nimport { DEFAULT_HOST } from './constants';\n\n/**\n * Firebase Storage location data.\n *\n * @internal\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, host: string): Location {\n let bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString, host);\n } catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n } else {\n throw invalidDefaultBucket(bucketString);\n }\n }\n\n static makeFromUrl(url: string, host: 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 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 firebaseStorageHost = host.replace(/[.]/g, '\\\\.');\n const firebaseStoragePath = '(/([^?#]*).*)?$';\n const firebaseStorageRegExp = new RegExp(\n `^https?://${firebaseStorageHost}/${version}/b/${bucketDomain}/o${firebaseStoragePath}`,\n 'i'\n );\n const firebaseStorageIndices = { bucket: 1, path: 3 };\n\n const cloudStorageHost =\n host === DEFAULT_HOST\n ? '(?:storage.googleapis.com|storage.cloud.google.com)'\n : host;\n const cloudStoragePath = '([^?#]*)';\n const cloudStorageRegExp = new RegExp(\n `^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`,\n 'i'\n );\n const cloudStorageIndices = { bucket: 1, path: 2 };\n\n const groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n {\n regex: firebaseStorageRegExp,\n indices: firebaseStorageIndices,\n postModify: httpModify\n },\n {\n regex: cloudStorageRegExp,\n indices: cloudStorageIndices,\n postModify: httpModify\n }\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 invalidUrl(url);\n }\n return location;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { StorageError } from './error';\nimport { Request } from './request';\n\n/**\n * A request whose promise always fails.\n */\nexport class FailRequest<T> implements Request<T> {\n promise_: Promise<T>;\n\n constructor(error: StorageError) {\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { invalidArgument } from './error';\n\nexport function isJustDef<T>(p: T | null | undefined): p is T | null {\n return p !== void 0;\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isFunction(p: unknown): p is Function {\n return typeof p === 'function';\n}\n\nexport function isNonArrayObject(p: unknown): boolean {\n return typeof p === 'object' && !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 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\nexport function validateNumber(\n argument: string,\n minValue: number,\n maxValue: number,\n value: number\n): void {\n if (value < minValue) {\n throw invalidArgument(\n `Invalid value for '${argument}'. Expected ${minValue} or greater.`\n );\n }\n if (value > maxValue) {\n throw invalidArgument(\n `Invalid value for '${argument}'. Expected ${maxValue} or less.`\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport { UrlParams } from './requestinfo';\n\nexport function makeUrl(\n urlPart: string,\n host: string,\n protocol: string\n): string {\n let origin = host;\n if (protocol == null) {\n origin = `https://${host}`;\n }\n return `${protocol}://${origin}/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 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 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks the status code to see if the action should be retried.\n *\n * @param status Current HTTP status code returned by server.\n * @param additionalRetryCodes additional retry codes to check against\n */\nexport function isRetryStatusCode(\n status: number,\n additionalRetryCodes: number[]\n): 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 isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;\n return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\n\nimport { id as backoffId, start, stop } from './backoff';\nimport { appDeleted, canceled, retryLimitExceeded, unknown } from './error';\nimport { ErrorHandler, RequestHandler, RequestInfo } from './requestinfo';\nimport { isJustDef } from './type';\nimport { makeQueryString } from './url';\nimport { Connection, ErrorCode, Headers, ConnectionType } from './connection';\nimport { isRetryStatusCode } from './utils';\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 * Handles network logic for all Storage Requests, including error reporting and\n * retries with backoff.\n *\n * @param I - the type of the backend's network response.\n * @param - O the output type used by the rest of the SDK. The conversion\n * happens in the specified `callback_`.\n */\nclass NetworkRequest<I extends ConnectionType, O> implements Request<O> {\n private pendingConnection_: Connection<I> | null = null;\n private backoffId_: backoffId | null = null;\n private resolve_!: (value?: O | PromiseLike<O>) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private reject_!: (reason?: any) => void;\n private canceled_: boolean = false;\n private appDelete_: boolean = false;\n private promise_: Promise<O>;\n\n constructor(\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 callback_: RequestHandler<I, O>,\n private errorCallback_: ErrorHandler | null,\n private timeout_: number,\n private progressCallback_: ((p1: number, p2: number) => void) | null,\n private connectionFactory_: () => Connection<I>,\n private retry = true\n ) {\n this.promise_ = new Promise((resolve, reject) => {\n this.resolve_ = resolve as (value?: O | PromiseLike<O>) => void;\n this.reject_ = reject;\n this.start_();\n });\n }\n\n /**\n * Actually starts the retry loop.\n */\n private start_(): void {\n const doTheRequest: (\n backoffCallback: (success: boolean, ...p2: unknown[]) => void,\n canceled: boolean\n ) => void = (backoffCallback, canceled) => {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n const connection = this.connectionFactory_();\n this.pendingConnection_ = connection;\n\n const progressListener: (\n progressEvent: ProgressEvent\n ) => void = progressEvent => {\n const loaded = progressEvent.loaded;\n const total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (this.progressCallback_ !== null) {\n this.progressCallback_(loaded, total);\n }\n };\n if (this.progressCallback_ !== null) {\n connection.addUploadProgressListener(progressListener);\n }\n\n // connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n connection\n .send(this.url_, this.method_, this.body_, this.headers_)\n .then(() => {\n if (this.progressCallback_ !== null) {\n connection.removeUploadProgressListener(progressListener);\n }\n this.pendingConnection_ = null;\n const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;\n const status = connection.getStatus();\n if (\n !hitServer ||\n (isRetryStatusCode(status, this.additionalRetryCodes_) &&\n this.retry)\n ) {\n const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(\n false,\n new RequestEndStatus(false, null, wasCanceled)\n );\n return;\n }\n const successCode = this.successCodes_.indexOf(status) !== -1;\n backoffCallback(true, new RequestEndStatus(successCode, connection));\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 const backoffDone: (\n requestWentThrough: boolean,\n status: RequestEndStatus<I>\n ) => void = (requestWentThrough, status) => {\n const resolve = this.resolve_;\n const reject = this.reject_;\n const connection = status.connection as Connection<I>;\n if (status.wasSuccessCode) {\n try {\n const result = this.callback_(connection, connection.getResponse());\n if (isJustDef(result)) {\n resolve(result);\n } else {\n resolve();\n }\n } catch (e) {\n reject(e);\n }\n } else {\n if (connection !== null) {\n const err = unknown();\n err.serverResponse = connection.getErrorText();\n if (this.errorCallback_) {\n reject(this.errorCallback_(connection, err));\n } else {\n reject(err);\n }\n } else {\n if (status.canceled) {\n const err = this.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_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n }\n\n /** @inheritDoc */\n getPromise(): Promise<O> {\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 stop(this.backoffId_);\n }\n if (this.pendingConnection_ !== null) {\n this.pendingConnection_.abort();\n }\n }\n}\n\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled - Defaults to false.\n */\nexport class RequestEndStatus<I extends ConnectionType> {\n /**\n * True if the request was canceled.\n */\n canceled: boolean;\n\n constructor(\n public wasSuccessCode: boolean,\n public connection: Connection<I> | 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_(\n headers: Headers,\n firebaseVersion?: string\n): void {\n headers['X-Firebase-Storage-Version'] =\n 'webjs/' + (firebaseVersion ?? 'AppManager');\n}\n\nexport function addGmpidHeader_(headers: Headers, appId: string | null): void {\n if (appId) {\n headers['X-Firebase-GMPID'] = appId;\n }\n}\n\nexport function addAppCheckHeader_(\n headers: Headers,\n appCheckToken: string | null\n): void {\n if (appCheckToken !== null) {\n headers['X-Firebase-AppCheck'] = appCheckToken;\n }\n}\n\nexport function makeRequest<I extends ConnectionType, O>(\n requestInfo: RequestInfo<I, O>,\n appId: string | null,\n authToken: string | null,\n appCheckToken: string | null,\n requestFactory: () => Connection<I>,\n firebaseVersion?: string,\n retry = true\n): Request<O> {\n const queryPart = makeQueryString(requestInfo.urlParams);\n const url = requestInfo.url + queryPart;\n const headers = Object.assign({}, requestInfo.headers);\n addGmpidHeader_(headers, appId);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers, firebaseVersion);\n addAppCheckHeader_(headers, appCheckToken);\n return new NetworkRequest<I, O>(\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 requestFactory,\n retry\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 * Accepts a callback for an action to perform (`doRequest`),\n * and then a callback for when the backoff has completed (`backoffCompleteCb`).\n * The callback sent to start requires an argument to call (`onRequestComplete`).\n * When `start` calls `doRequest`, it passes a callback for when the request has\n * completed, `onRequestComplete`. Based on this, the backoff continues, with\n * another call to `doRequest` and the above loop continues until the timeout\n * is hit, or a successful response occurs.\n * @description\n * @param doRequest Callback to perform request\n * @param backoffCompleteCb Callback to call when backoff has been completed\n */\nexport function start(\n doRequest: (\n onRequestComplete: (success: boolean) => void,\n canceled: boolean\n ) => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n backoffCompleteCb: (...args: any[]) => unknown,\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 retryTimeoutId: any = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let globalTimeoutId: 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 function triggerCallback(...args: any[]): void {\n if (!triggeredCallback) {\n triggeredCallback = true;\n backoffCompleteCb.apply(null, args);\n }\n }\n\n function callWithDelay(millis: number): void {\n retryTimeoutId = setTimeout(() => {\n retryTimeoutId = null;\n doRequest(responseHandler, canceled());\n }, millis);\n }\n\n function clearGlobalTimeout(): void {\n if (globalTimeoutId) {\n clearTimeout(globalTimeoutId);\n }\n }\n\n function responseHandler(success: boolean, ...args: any[]): void {\n if (triggeredCallback) {\n clearGlobalTimeout();\n return;\n }\n if (success) {\n clearGlobalTimeout();\n triggerCallback.call(null, success, ...args);\n return;\n }\n const mustStop = canceled() || hitTimeout;\n if (mustStop) {\n clearGlobalTimeout();\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 clearGlobalTimeout();\n if (triggeredCallback) {\n return;\n }\n if (retryTimeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(retryTimeoutId);\n callWithDelay(0);\n } else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n globalTimeoutId = 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @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 { isNativeBlobDefined } from './type';\nimport { StorageErrorCode, StorageError } from './error';\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 (isNativeBlobDefined()) {\n return new Blob(args);\n } else {\n throw new StorageError(\n StorageErrorCode.UNSUPPORTED_ENVIRONMENT,\n \"This browser doesn't seem to support creating Blobs\"\n );\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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { missingPolyFill } from '../../implementation/error';\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n if (typeof atob === 'undefined') {\n throw missingPolyFill('base-64');\n }\n return atob(encoded);\n}\n\nexport function decodeUint8Array(data: Uint8Array): string {\n return new TextDecoder().decode(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { unknown, invalidFormat } from './error';\nimport { decodeBase64 } from '../platform/base64';\n\n/**\n * An enumeration of the possible string formats for upload.\n * @public\n */\nexport type StringFormat = (typeof StringFormat)[keyof typeof StringFormat];\n/**\n * An enumeration of the possible string formats for upload.\n * @public\n */\nexport const StringFormat = {\n /**\n * Indicates the string should be interpreted \"raw\", that is, as normal text.\n * The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte\n * sequence.\n * Example: The string 'Hello! \\\\ud83d\\\\ude0a' becomes the byte sequence\n * 48 65 6c 6c 6f 21 20 f0 9f 98 8a\n */\n RAW: 'raw',\n /**\n * Indicates the string should be interpreted as base64-encoded data.\n * Padding characters (trailing '='s) are optional.\n * Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence\n * ad 69 8e fb e1 3a b7 bf eb 97\n */\n BASE64: 'base64',\n /**\n * Indicates the string should be interpreted as base64url-encoded data.\n * Padding characters (trailing '='s) are optional.\n * Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence\n * ad 69 8e fb e1 3a b7 bf eb 97\n */\n BASE64URL: 'base64url',\n /**\n * Indicates the string is a data URL, such as one obtained from\n * canvas.toDataURL().\n * Example: the string 'data:application/octet-stream;base64,aaaa'\n * becomes the byte sequence\n * 69 a6 9a\n * (the content-type \"application/octet-stream\" is also applied, but can\n * be overridden in the metadata object).\n */\n DATA_URL: 'data_url'\n} as const;\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\n/**\n * @internal\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 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 invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\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 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 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 = decodeBase64(value);\n } catch (e) {\n if ((e as Error).message.includes('polyfill')) {\n throw e;\n }\n throw 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\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 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 { sliceBlob, getBlob } from './fs';\nimport { StringFormat, dataFromString } from './string';\nimport { isNativeBlob, isNativeBlobDefined, isString } 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 *\n * @internal\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 (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 (isNativeBlob(this.data_)) {\n const realBlob = this.data_ as Blob;\n const sliced = 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 (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(getBlob.apply(null, blobby));\n } else {\n const uint8Arrays: Uint8Array[] = args.map(\n (val: string | FbsBlob): Uint8Array => {\n if (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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { isNonArrayObject } 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 (isNonArrayObject(obj)) {\n return obj;\n } else {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Documentation for the metadata format\n */\nimport { Metadata } from '../metadata';\n\nimport { jsonObjectOrNull } from './json';\nimport { Location } from './location';\nimport { lastComponent } from './path';\nimport { isString } from './type';\nimport { makeUrl, makeQueryString } from './url';\nimport { Reference } from '../reference';\nimport { FirebaseStorageImpl } from '../service';\n\nexport function noXform_<T>(metadata: Metadata, value: T): T {\n return value;\n}\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 (!isString(fullPath) || fullPath.length < 2) {\n return fullPath;\n } else {\n return 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\n ): number | undefined {\n if (size !== undefined) {\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, service: FirebaseStorageImpl): 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 service._makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\n\nexport function fromResource(\n service: FirebaseStorageImpl,\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, service);\n return metadata;\n}\n\nexport function fromResourceString(\n service: FirebaseStorageImpl,\n resourceString: string,\n mappings: Mappings\n): Metadata | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = obj as Metadata;\n return fromResource(service, resource, mappings);\n}\n\nexport function downloadUrlFromResourceString(\n metadata: Metadata,\n resourceString: string,\n host: string,\n protocol: string\n): string | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n if (!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 = makeUrl(urlPart, host, protocol);\n const queryString = makeQueryString({\n alt: 'media',\n token\n });\n return base + queryString;\n });\n return urls[0];\n}\n\nexport function toResourceString(\n metadata: Partial<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","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Documentation for the listOptions and listResult format\n */\nimport { Location } from './location';\nimport { jsonObjectOrNull } from './json';\nimport { ListResult } from '../list';\nimport { FirebaseStorageImpl } from '../service';\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 PREFIXES_KEY = 'prefixes';\nconst ITEMS_KEY = 'items';\n\nfunction fromBackendResponse(\n service: FirebaseStorageImpl,\n bucket: string,\n resource: ListResultResponse\n): ListResult {\n const listResult: ListResult = {\n prefixes: [],\n items: [],\n nextPageToken: resource['nextPageToken']\n };\n if (resource[PREFIXES_KEY]) {\n for (const path of resource[PREFIXES_KEY]) {\n const pathWithoutTrailingSlash = path.replace(/\\/$/, '');\n const reference = service._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 = service._makeStorageReference(\n new Location(bucket, item['name'])\n );\n listResult.items.push(reference);\n }\n }\n return listResult;\n}\n\nexport function fromResponseString(\n service: FirebaseStorageImpl,\n bucket: string,\n resourceString: string\n): ListResult | null {\n const obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = obj as unknown as ListResultResponse;\n return fromBackendResponse(service, bucket, resource);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { StorageError } from './error';\nimport { Headers, Connection, ConnectionType } from './connection';\n\n/**\n * Type for url params stored in RequestInfo.\n */\nexport interface UrlParams {\n [name: string]: string | number;\n}\n\n/**\n * A function that converts a server response to the API type expected by the\n * SDK.\n *\n * @param I - the type of the backend's network response\n * @param O - the output response type used by the rest of the SDK.\n */\nexport type RequestHandler<I extends ConnectionType, O> = (\n connection: Connection<I>,\n response: I\n) => O;\n\n/** A function to handle an error. */\nexport type ErrorHandler = (\n connection: Connection<ConnectionType>,\n response: StorageError\n) => StorageError;\n\n/**\n * Contains a fully specified request.\n *\n * @param I - the type of the backend's network response.\n * @param O - the output response type used by the rest of the SDK.\n */\nexport class RequestInfo<I extends ConnectionType, O> {\n urlParams: UrlParams = {};\n headers: Headers = {};\n body: Blob | string | Uint8Array | null = null;\n errorHandler: ErrorHandler | 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: RequestHandler<I, O>,\n public timeout: number\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines methods for interacting with the network.\n */\n\nimport { Metadata } from '../metadata';\nimport { ListResult } from '../list';\nimport { FbsBlob } from './blob';\nimport {\n StorageError,\n cannotSliceBlob,\n unauthenticated,\n quotaExceeded,\n unauthorized,\n objectNotFound,\n serverFileWrongSize,\n unknown,\n unauthorizedApp\n} from './error';\nimport { Location } from './location';\nimport {\n Mappings,\n fromResourceString,\n downloadUrlFromResourceString,\n toResourceString\n} from './metadata';\nimport { fromResponseString } from './list';\nimport { RequestInfo, UrlParams } from './requestinfo';\nimport { isString } from './type';\nimport { makeUrl } from './url';\nimport { Connection, ConnectionType } from './connection';\nimport { FirebaseStorageImpl } from '../service';\n\n/**\n * Throws the UNKNOWN StorageError if cndn is false.\n */\nexport function handlerCheck(cndn: boolean): void {\n if (!cndn) {\n throw unknown();\n }\n}\n\nexport function metadataHandler(\n service: FirebaseStorageImpl,\n mappings: Mappings\n): (p1: Connection<string>, p2: string) => Metadata {\n function handler(xhr: Connection<string>, text: string): Metadata {\n const metadata = fromResourceString(service, text, mappings);\n handlerCheck(metadata !== null);\n return metadata as Metadata;\n }\n return handler;\n}\n\nexport function listHandler(\n service: FirebaseStorageImpl,\n bucket: string\n): (p1: Connection<string>, p2: string) => ListResult {\n function handler(xhr: Connection<string>, text: string): ListResult {\n const listResult = fromResponseString(service, bucket, text);\n handlerCheck(listResult !== null);\n return listResult as ListResult;\n }\n return handler;\n}\n\nexport function downloadUrlHandler(\n service: FirebaseStorageImpl,\n mappings: Mappings\n): (p1: Connection<string>, p2: string) => string | null {\n function handler(xhr: Connection<string>, text: string): string | null {\n const metadata = fromResourceString(service, text, mappings);\n handlerCheck(metadata !== null);\n return downloadUrlFromResourceString(\n metadata as Metadata,\n text,\n service.host,\n service._protocol\n );\n }\n return handler;\n}\n\nexport function sharedErrorHandler(\n location: Location\n): (p1: Connection<ConnectionType>, p2: StorageError) => StorageError {\n function errorHandler(\n xhr: Connection<ConnectionType>,\n err: StorageError\n ): StorageError {\n let newErr: StorageError;\n if (xhr.getStatus() === 401) {\n if (\n // This exact message string is the only consistent part of the\n // server's error response that identifies it as an App Check error.\n xhr.getErrorText().includes('Firebase App Check token is invalid')\n ) {\n newErr = unauthorizedApp();\n } else {\n newErr = unauthenticated();\n }\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.status = xhr.getStatus();\n newErr.serverResponse = err.serverResponse;\n return newErr;\n }\n return errorHandler;\n}\n\nexport function objectErrorHandler(\n location: Location\n): (p1: Connection<ConnectionType>, p2: StorageError) => StorageError {\n const shared = sharedErrorHandler(location);\n\n function errorHandler(\n xhr: Connection<ConnectionType>,\n err: StorageError\n ): StorageError {\n let newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.serverResponse = err.serverResponse;\n return newErr;\n }\n return errorHandler;\n}\n\nexport function getMetadata(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings\n): RequestInfo<string, Metadata> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function list(\n service: FirebaseStorageImpl,\n location: Location,\n delimiter?: string,\n pageToken?: string | null,\n maxResults?: number | null\n): RequestInfo<string, 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 = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n listHandler(service, location.bucket),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\nexport function getBytes<I extends ConnectionType>(\n service: FirebaseStorageImpl,\n location: Location,\n maxDownloadSizeBytes?: number\n): RequestInfo<I, I> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n (_: Connection<I>, data: I) => data,\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n if (maxDownloadSizeBytes !== undefined) {\n requestInfo.headers['Range'] = `bytes=0-${maxDownloadSizeBytes}`;\n requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];\n }\n return requestInfo;\n}\n\nexport function getDownloadUrl(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings\n): RequestInfo<string, string | null> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'GET';\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n downloadUrlHandler(service, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function updateMetadata(\n service: FirebaseStorageImpl,\n location: Location,\n metadata: Partial<Metadata>,\n mappings: Mappings\n): RequestInfo<string, Metadata> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'PATCH';\n const body = toResourceString(metadata, mappings);\n const headers = { 'Content-Type': 'application/json; charset=utf-8' };\n const timeout = service.maxOperationRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, 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 service: FirebaseStorageImpl,\n location: Location\n): RequestInfo<string, void> {\n const urlPart = location.fullServerUrl();\n const url = makeUrl(urlPart, service.host, service._protocol);\n const method = 'DELETE';\n const timeout = service.maxOperationRetryTime;\n\n function handler(_xhr: Connection<string>, _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\n/**\n * Prepare RequestInfo for uploads as Content-Type: multipart.\n */\nexport function multipartUpload(\n service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo<string, 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 = str + Math.random().toString().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 = 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 = makeUrl(urlPart, service.host, service._protocol);\n const method = 'POST';\n const timeout = service.maxUploadRetryTime;\n const requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(service, 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 */\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_(\n xhr: Connection<string>,\n allowed?: string[]\n): 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 service: FirebaseStorageImpl,\n location: Location,\n mappings: Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo<string, string> {\n const urlPart = location.bucketOnlyServerUrl();\n const metadataForUpload = metadataForUpload_(location, blob, metadata);\n const urlParams: UrlParams = { name: metadataForUpload['fullPath']! };\n const url = makeUrl(urlPart, service.host, service._protocol);\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 = toResourceString(metadataForUpload, mappings);\n const timeout = service.maxUploadRetryTime;\n\n function handler(xhr: Connection<string>): string {\n checkResumeHeader_(xhr);\n let url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n } catch (e) {\n handlerCheck(false);\n }\n handlerCheck(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 service: FirebaseStorageImpl,\n location: Location,\n url: string,\n blob: FbsBlob\n): RequestInfo<string, ResumableUploadStatus> {\n const headers = { 'X-Goog-Upload-Command': 'query' };\n\n function handler(xhr: Connection<string>): 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 = service.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 RESUMABLE_UPLOAD_CHUNK_SIZE: 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 service: FirebaseStorageImpl,\n url: string,\n blob: FbsBlob,\n chunkSize: number,\n mappings: Mappings,\n status?: ResumableUploadStatus | null,\n progressCallback?: ((p1: number, p2: number) => void) | null\n): RequestInfo<string, 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 let uploadCommand = '';\n if (bytesToUpload === 0) {\n uploadCommand = 'finalize';\n } else if (bytesLeft === bytesToUpload) {\n uploadCommand = 'upload, finalize';\n } else {\n uploadCommand = 'upload';\n }\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(\n xhr: Connection<string>,\n text: string\n ): 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(service, 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 = service.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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Enumerations used for upload tasks.\n */\n\n/**\n * An event that is triggered on a task.\n * @internal\n */\nexport type TaskEvent = string;\n\n/**\n * An event that is triggered on a task.\n * @internal\n */\nexport const TaskEvent = {\n /**\n * For this event,\n * <ul>\n * <li>The `next` function is triggered on progress updates and when the\n * task is paused/resumed with an `UploadTaskSnapshot` as the first\n * argument.</li>\n * <li>The `error` function is triggered if the upload is canceled or fails\n * for another reason.</li>\n * <li>The `complete` function is triggered if the upload completes\n * successfully.</li>\n * </ul>\n */\n STATE_CHANGED: 'state_changed'\n};\n\n/**\n * Internal enum for task state.\n */\nexport const enum 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 * Represents the current state of a running upload.\n * @internal\n */\nexport type TaskState = (typeof TaskState)[keyof typeof TaskState];\n\n// type keys = keyof TaskState\n/**\n * Represents the current state of a running upload.\n * @internal\n */\nexport const TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n\n /** The task was paused by the user. */\n PAUSED: 'paused',\n\n /** The task completed successfully. */\n SUCCESS: 'success',\n\n /** The task was canceled. */\n CANCELED: 'canceled',\n\n /** The task failed with an error. */\n ERROR: 'error'\n} as const;\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { isFunction } from './type';\nimport { StorageError } from './error';\n\n/**\n * Function that is called once for each value in a stream of values.\n */\nexport type NextFn<T> = (value: T) => void;\n\n/**\n * A function that is called with a `StorageError`\n * if the event stream ends due to an error.\n */\nexport type ErrorFn = (error: StorageError) => void;\n\n/**\n * A function that is called if the event stream ends normally.\n */\nexport type CompleteFn = () => void;\n\n/**\n * Unsubscribes from a stream.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * An observer identical to the `Observer` defined in packages/util except the\n * error passed into the ErrorFn is specifically a `StorageError`.\n */\nexport interface StorageObserver<T> {\n /**\n * Function that is called once for each value in the event stream.\n */\n next?: NextFn<T>;\n /**\n * A function that is called with a `StorageError`\n * if the event stream ends due to an error.\n */\n error?: ErrorFn;\n /**\n * A function that is called if the event stream ends normally.\n */\n complete?: CompleteFn;\n}\n\n/**\n * Subscribes to an event stream.\n */\nexport type Subscribe<T> = (\n next?: NextFn<T> | StorageObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n) => Unsubscribe;\n\nexport class Observer<T> implements StorageObserver<T> {\n next?: NextFn<T>;\n error?: ErrorFn;\n complete?: CompleteFn;\n\n constructor(\n nextOrObserver?: NextFn<T> | StorageObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n ) {\n const asFunctions =\n isFunction(nextOrObserver) || error != null || complete != null;\n if (asFunctions) {\n this.next = nextOrObserver as NextFn<T>;\n this.error = error ?? undefined;\n this.complete = complete ?? undefined;\n } else {\n const observer = nextOrObserver as {\n next?: NextFn<T>;\n error?: ErrorFn;\n complete?: CompleteFn;\n };\n this.next = observer.next;\n this.error = observer.error;\n this.complete = observer.complete;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 */\n// eslint-disable-next-line @typescript-eslint/ban-types\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Connection,\n ConnectionType,\n ErrorCode,\n Headers\n} from '../../implementation/connection';\nimport { internalError } from '../../implementation/error';\n\n/** An override for the text-based Connection. Used in tests. */\nlet textFactoryOverride: (() => Connection<string>) | null = null;\n\n/**\n * Network layer for browsers. We use this instead of goog.net.XhrIo because\n * goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.\n */\nabstract class XhrConnection<T extends ConnectionType>\n implements Connection<T>\n{\n protected xhr_: XMLHttpRequest;\n private errorCode_: ErrorCode;\n private sendPromise_: Promise<void>;\n protected sent_: boolean = false;\n\n constructor() {\n this.xhr_ = new XMLHttpRequest();\n this.initXhr();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = new Promise(resolve => {\n this.xhr_.addEventListener('abort', () => {\n this.errorCode_ = ErrorCode.ABORT;\n resolve();\n });\n this.xhr_.addEventListener('error', () => {\n this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve();\n });\n this.xhr_.addEventListener('load', () => {\n resolve();\n });\n });\n }\n\n abstract initXhr(): void;\n\n send(\n url: string,\n method: string,\n body?: ArrayBufferView | Blob | string,\n headers?: Headers\n ): Promise<void> {\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (headers !== undefined) {\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n this.xhr_.setRequestHeader(key, headers[key].toString());\n }\n }\n }\n if (body !== undefined) {\n this.xhr_.send(body);\n } else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n }\n\n getErrorCode(): ErrorCode {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n }\n\n getStatus(): number {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n } catch (e) {\n return -1;\n }\n }\n\n getResponse(): T {\n if (!this.sent_) {\n throw internalError('cannot .getResponse() before sending');\n }\n return this.xhr_.response;\n }\n\n getErrorText(): string {\n if (!this.sent_) {\n throw internalError('cannot .getErrorText() before sending');\n }\n return this.xhr_.statusText;\n }\n\n /** Aborts the request. */\n abort(): void {\n this.xhr_.abort();\n }\n\n getResponseHeader(header: string): string | null {\n return this.xhr_.getResponseHeader(header);\n }\n\n addUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n if (this.xhr_.upload != null) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n }\n\n removeUploadProgressListener(listener: (p1: ProgressEvent) => void): void {\n if (this.xhr_.upload != null) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n }\n}\n\nexport class XhrTextConnection extends XhrConnection<string> {\n initXhr(): void {\n this.xhr_.responseType = 'text';\n }\n}\n\nexport function newTextConnection(): Connection<string> {\n return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();\n}\n\nexport class XhrBytesConnection extends XhrConnection<ArrayBuffer> {\n private data_?: ArrayBuffer;\n\n initXhr(): void {\n this.xhr_.responseType = 'arraybuffer';\n }\n}\n\nexport function newBytesConnection(): Connection<ArrayBuffer> {\n return new XhrBytesConnection();\n}\n\nexport class XhrBlobConnection extends XhrConnection<Blob> {\n initXhr(): void {\n this.xhr_.responseType = 'blob';\n }\n}\n\nexport function newBlobConnection(): Connection<Blob> {\n return new XhrBlobConnection();\n}\n\nexport function newStreamConnection(): Connection<NodeJS.ReadableStream> {\n throw new Error('Streams are only supported on Node');\n}\n\nexport function injectTestConnection(\n factory: (() => Connection<string>) | null\n): void {\n textFactoryOverride = factory;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\nimport { FbsBlob } from './implementation/blob';\nimport {\n canceled,\n StorageErrorCode,\n StorageError,\n retryLimitExceeded\n} from './implementation/error';\nimport {\n InternalTaskState,\n TaskEvent,\n TaskState,\n taskStateFromInternalTaskState\n} from './implementation/taskenums';\nimport { Metadata } from './metadata';\nimport {\n Observer,\n Subscribe,\n Unsubscribe,\n StorageObserver as StorageObserverInternal,\n NextFn\n} from './implementation/observer';\nimport { Request } from './implementation/request';\nimport { UploadTaskSnapshot, StorageObserver } from './public-types';\nimport { async as fbsAsync } from './implementation/async';\nimport { Mappings, getMappings } from './implementation/metadata';\nimport {\n createResumableUpload,\n getResumableUploadStatus,\n RESUMABLE_UPLOAD_CHUNK_SIZE,\n ResumableUploadStatus,\n continueResumableUpload,\n getMetadata,\n multipartUpload\n} from './implementation/requests';\nimport { Reference } from './reference';\nimport { newTextConnection } from './platform/connection';\nimport { isRetryStatusCode } from './implementation/utils';\nimport { CompleteFn } from '@firebase/util';\nimport { DEFAULT_MIN_SLEEP_TIME_MILLIS } from './implementation/constants';\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 * @internal\n */\nexport class UploadTask {\n private _ref: Reference;\n /**\n * The data to be uploaded.\n */\n _blob: FbsBlob;\n /**\n * Metadata related to the upload.\n */\n _metadata: Metadata | null;\n private _mappings: Mappings;\n /**\n * Number of bytes transferred so far.\n */\n _transferred: number = 0;\n private _needToFetchStatus: boolean = false;\n private _needToFetchMetadata: boolean = false;\n private _observers: Array<StorageObserverInternal<UploadTaskSnapshot>> = [];\n private _resumable: boolean;\n /**\n * Upload state.\n */\n _state: InternalTaskState;\n private _error?: StorageError = undefined;\n private _uploadUrl?: string = undefined;\n private _request?: Request<unknown> = undefined;\n private _chunkMultiplier: number = 1;\n private _errorHandler: (p1: StorageError) => void;\n private _metadataErrorHandler: (p1: StorageError) => void;\n private _resolve?: (p1: UploadTaskSnapshot) => void = undefined;\n private _reject?: (p1: StorageError) => void = undefined;\n private pendingTimeout?: ReturnType<typeof setTimeout>;\n private _promise: Promise<UploadTaskSnapshot>;\n\n private sleepTime: number;\n\n private maxSleepTime: number;\n\n isExponentialBackoffExpired(): boolean {\n return this.sleepTime > this.maxSleepTime;\n }\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(ref: Reference, blob: FbsBlob, metadata: Metadata | null = null) {\n this._ref = ref;\n this._blob = blob;\n this._metadata = metadata;\n this._mappings = getMappings();\n this._resumable = this._shouldDoResumable(this._blob);\n this._state = InternalTaskState.RUNNING;\n this._errorHandler = error => {\n this._request = undefined;\n this._chunkMultiplier = 1;\n if (error._codeEquals(StorageErrorCode.CANCELED)) {\n this._needToFetchStatus = true;\n this.completeTransitions_();\n } else {\n const backoffExpired = this.isExponentialBackoffExpired();\n if (isRetryStatusCode(error.status, [])) {\n if (backoffExpired) {\n error = retryLimitExceeded();\n } else {\n this.sleepTime = Math.max(\n this.sleepTime * 2,\n DEFAULT_MIN_SLEEP_TIME_MILLIS\n );\n this._needToFetchStatus = true;\n this.completeTransitions_();\n return;\n }\n }\n this._error = error;\n this._transition(InternalTaskState.ERROR);\n }\n };\n this._metadataErrorHandler = error => {\n this._request = undefined;\n if (error._codeEquals(StorageErrorCode.CANCELED)) {\n this.completeTransitions_();\n } else {\n this._error = error;\n this._transition(InternalTaskState.ERROR);\n }\n };\n this.sleepTime = 0;\n this.maxSleepTime = this._ref.storage.maxUploadRetryTime;\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 !== undefined) {\n return;\n }\n if (this._resumable) {\n if (this._uploadUrl === undefined) {\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.pendingTimeout = setTimeout(() => {\n this.pendingTimeout = undefined;\n this._continueUpload();\n }, this.sleepTime);\n }\n }\n }\n } else {\n this._oneShotUpload();\n }\n }\n\n private _resolveToken(\n callback: (authToken: string | null, appCheckToken: string | null) => void\n ): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all([\n this._ref.storage._getAuthToken(),\n this._ref.storage._getAppCheckToken()\n ]).then(([authToken, appCheckToken]) => {\n switch (this._state) {\n case InternalTaskState.RUNNING:\n callback(authToken, appCheckToken);\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, appCheckToken) => {\n const requestInfo = createResumableUpload(\n this._ref.storage,\n this._ref._location,\n this._mappings,\n this._blob,\n this._metadata\n );\n const createRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = createRequest;\n createRequest.getPromise().then((url: string) => {\n this._request = undefined;\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, appCheckToken) => {\n const requestInfo = getResumableUploadStatus(\n this._ref.storage,\n this._ref._location,\n url,\n this._blob\n );\n const statusRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = statusRequest;\n statusRequest.getPromise().then(status => {\n status = status as ResumableUploadStatus;\n this._request = undefined;\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 = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\n const status = new 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, appCheckToken) => {\n let requestInfo;\n try {\n requestInfo = continueResumableUpload(\n this._ref._location,\n this._ref.storage,\n url,\n this._blob,\n chunkSize,\n this._mappings,\n status,\n this._makeProgressCallback()\n );\n } catch (e) {\n this._error = e as StorageError;\n this._transition(InternalTaskState.ERROR);\n return;\n }\n const uploadRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken,\n /*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.\n );\n this._request = uploadRequest;\n uploadRequest.getPromise().then((newStatus: ResumableUploadStatus) => {\n this._increaseMultiplier();\n this._request = undefined;\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 = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;\n\n // Max chunk size is 32M.\n if (currentSize * 2 < 32 * 1024 * 1024) {\n this._chunkMultiplier *= 2;\n }\n }\n\n private _fetchMetadata(): void {\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = getMetadata(\n this._ref.storage,\n this._ref._location,\n this._mappings\n );\n const metadataRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = metadataRequest;\n metadataRequest.getPromise().then(metadata => {\n this._request = undefined;\n this._metadata = metadata;\n this._transition(InternalTaskState.SUCCESS);\n }, this._metadataErrorHandler);\n });\n }\n\n private _oneShotUpload(): void {\n this._resolveToken((authToken, appCheckToken) => {\n const requestInfo = multipartUpload(\n this._ref.storage,\n this._ref._location,\n this._mappings,\n this._blob,\n this._metadata\n );\n const multipartRequest = this._ref.storage._makeRequest(\n requestInfo,\n newTextConnection,\n authToken,\n appCheckToken\n );\n this._request = multipartRequest;\n multipartRequest.getPromise().then(metadata => {\n this._request = undefined;\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 case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this._state = state;\n if (this._request !== undefined) {\n this._request.cancel();\n } else if (this.pendingTimeout) {\n clearTimeout(this.pendingTimeout);\n this.pendingTimeout = undefined;\n this.completeTransitions_();\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 /**\n * A snapshot of the current task state.\n */\n get snapshot(): UploadTaskSnapshot {\n const externalState = taskStateFromInternalTaskState(this._state);\n return {\n bytesTransferred: this._transferred,\n totalBytes: this._blob.size(),\n state: externalState,\n metadata: this._metadata!,\n task: this,\n ref: this._ref\n };\n }\n\n /**\n * Adds a callback for an event.\n * @param type - The type of event to listen for.\n * @param nextOrObserver -\n * The `next` function, which gets called for each item in\n * the event stream, or an observer object with some or all of these three\n * properties (`next`, `error`, `complete`).\n * @param error - A function that gets called with a `StorageError`\n * if the event stream ends due to an error.\n * @param completed - A function that gets called if the\n * event stream ends normally.\n * @returns\n * If only the event argument is passed, returns a function you can use to\n * add callbacks (see the examples above). If more than just the event\n * argument is passed, returns a function you can call to unregister the\n * callbacks.\n */\n on(\n type: TaskEvent,\n nextOrObserver?:\n | StorageObserver<UploadTaskSnapshot>\n | null\n | ((snapshot: UploadTaskSnapshot) => unknown),\n error?: ((a: StorageError) => unknown) | null,\n completed?: CompleteFn | null\n ): Unsubscribe | Subscribe<UploadTaskSnapshot> {\n // Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.\n const observer = new Observer(\n (nextOrObserver as\n | StorageObserverInternal<UploadTaskSnapshot>\n | NextFn<UploadTaskSnapshot>) || undefined,\n error || undefined,\n completed || undefined\n );\n this._addObserver(observer);\n return () => {\n this._removeObserver(observer);\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: StorageError) => 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: StorageError) => 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 !== undefined) {\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: StorageError) => void;\n fbsAsync(toCall.bind(null, this._error as StorageError))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this._resolve = undefined;\n this._reject = undefined;\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(\n observer.error.bind(observer, this._error as StorageError)\n )();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error) {\n fbsAsync(\n observer.error.bind(observer, this._error as StorageError)\n )();\n }\n }\n }\n\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @returns True if the operation took effect, false if ignored.\n */\n resume(): boolean {\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 * @returns True if the operation took effect, false if ignored.\n */\n pause(): boolean {\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 * @returns True if the operation took effect, false if ignored.\n */\n cancel(): boolean {\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Defines the Firebase StorageReference class.\n */\n\nimport { PassThrough, Transform, TransformOptions } from 'stream';\n\nimport { FbsBlob } from './implementation/blob';\nimport { Location } from './implementation/location';\nimport { getMappings } from './implementation/metadata';\nimport { child, lastComponent, parent } from './implementation/path';\nimport {\n deleteObject as requestsDeleteObject,\n getBytes,\n getDownloadUrl as requestsGetDownloadUrl,\n getMetadata as requestsGetMetadata,\n list as requestsList,\n multipartUpload,\n updateMetadata as requestsUpdateMetadata\n} from './implementation/requests';\nimport { ListOptions, UploadResult } from './public-types';\nimport { dataFromString, StringFormat } from './implementation/string';\nimport { Metadata } from './metadata';\nimport { FirebaseStorageImpl } from './service';\nimport { ListResult } from './list';\nimport { UploadTask } from './task';\nimport { invalidRootOperation, noDownloadURL } from './implementation/error';\nimport { validateNumber } from './implementation/type';\nimport {\n newBlobConnection,\n newBytesConnection,\n newStreamConnection,\n newTextConnection\n} from './platform/connection';\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @internal\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 _location: Location;\n\n constructor(\n private _service: FirebaseStorageImpl,\n location: string | Location\n ) {\n if (location instanceof Location) {\n this._location = location;\n } else {\n this._location = Location.makeFromUrl(location, _service.host);\n }\n }\n\n /**\n * Returns 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 return 'gs://' + this._location.bucket + '/' + this._location.path;\n }\n\n protected _newRef(\n service: FirebaseStorageImpl,\n location: Location\n ): Reference {\n return new Reference(service, location);\n }\n\n /**\n * A reference to the root of this object's bucket.\n */\n get root(): Reference {\n const location = new Location(this._location.bucket, '');\n return this._newRef(this._service, location);\n }\n\n /**\n * The name of the bucket containing this reference's object.\n */\n get bucket(): string {\n return this._location.bucket;\n }\n\n /**\n * The full path of this object.\n */\n get fullPath(): string {\n return this._location.path;\n }\n\n /**\n * The short name of this object, which is the last component of the full path.\n * For example, if fullPath is 'full/path/image.png', name is 'image.png'.\n */\n get name(): string {\n return lastComponent(this._location.path);\n }\n\n /**\n * The `StorageService` instance this `StorageReference` is associated with.\n */\n get storage(): FirebaseStorageImpl {\n return this._service;\n }\n\n /**\n * A `StorageReference` pointing to the parent location of this `StorageReference`, or null if\n * this reference is the root.\n */\n get parent(): Reference | null {\n const newPath = parent(this._location.path);\n if (newPath === null) {\n return null;\n }\n const location = new Location(this._location.bucket, newPath);\n return new Reference(this._service, location);\n }\n\n /**\n * Utility function to throw an error in methods that do not accept a root reference.\n */\n _throwIfRoot(name: string): void {\n if (this._location.path === '') {\n throw invalidRootOperation(name);\n }\n }\n}\n\n/**\n * Download the bytes at the object's location.\n * @returns A Promise containing the downloaded bytes.\n */\nexport function getBytesInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): Promise<ArrayBuffer> {\n ref._throwIfRoot('getBytes');\n const requestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newBytesConnection)\n .then(bytes =>\n maxDownloadSizeBytes !== undefined\n ? // GCS may not honor the Range header for small files\n (bytes as ArrayBuffer).slice(0, maxDownloadSizeBytes)\n : (bytes as ArrayBuffer)\n );\n}\n\n/**\n * Download the bytes at the object's location.\n * @returns A Promise containing the downloaded blob.\n */\nexport function getBlobInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): Promise<Blob> {\n ref._throwIfRoot('getBlob');\n const requestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newBlobConnection)\n .then(blob =>\n maxDownloadSizeBytes !== undefined\n ? // GCS may not honor the Range header for small files\n (blob as Blob).slice(0, maxDownloadSizeBytes)\n : (blob as Blob)\n );\n}\n\n/** Stream the bytes at the object's location. */\nexport function getStreamInternal(\n ref: Reference,\n maxDownloadSizeBytes?: number\n): NodeJS.ReadableStream {\n ref._throwIfRoot('getStream');\n const requestInfo = getBytes(\n ref.storage,\n ref._location,\n maxDownloadSizeBytes\n );\n\n /** A transformer that passes through the first n bytes. */\n const newMaxSizeTransform: (n: number) => TransformOptions = n => {\n let missingBytes = n;\n return {\n transform(chunk, encoding, callback) {\n // GCS may not honor the Range header for small files\n if (chunk.length < missingBytes) {\n this.push(chunk);\n missingBytes -= chunk.length;\n } else {\n this.push(chunk.slice(0, missingBytes));\n this.emit('end');\n }\n callback();\n }\n } as TransformOptions;\n };\n\n const result =\n maxDownloadSizeBytes !== undefined\n ? new Transform(newMaxSizeTransform(maxDownloadSizeBytes))\n : new PassThrough();\n\n ref.storage\n .makeRequestWithTokens(requestInfo, newStreamConnection)\n .then(stream => (stream as NodeJS.ReadableStream).pipe(result))\n .catch(e => result.destroy(e));\n return result;\n}\n\n/**\n * Uploads data to this object's location.\n * The upload is not resumable.\n *\n * @param ref - StorageReference where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the newly uploaded data.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadBytes(\n ref: Reference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: Metadata\n): Promise<UploadResult> {\n ref._throwIfRoot('uploadBytes');\n const requestInfo = multipartUpload(\n ref.storage,\n ref._location,\n getMappings(),\n new FbsBlob(data, true),\n metadata\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newTextConnection)\n .then(finalMetadata => {\n return {\n metadata: finalMetadata,\n ref\n };\n });\n}\n\n/**\n * Uploads data to this object's location.\n * The upload can be paused and resumed, and exposes progress updates.\n * @public\n * @param ref - StorageReference where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the newly uploaded data.\n * @returns An UploadTask\n */\nexport function uploadBytesResumable(\n ref: Reference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: Metadata\n): UploadTask {\n ref._throwIfRoot('uploadBytesResumable');\n return new UploadTask(ref, new FbsBlob(data), metadata);\n}\n\n/**\n * Uploads a string to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - StorageReference where string should be uploaded.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @param metadata - Metadata for the newly uploaded string.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadString(\n ref: Reference,\n value: string,\n format: StringFormat = StringFormat.RAW,\n metadata?: Metadata\n): Promise<UploadResult> {\n ref._throwIfRoot('uploadString');\n const data = dataFromString(format, value);\n const metadataClone = { ...metadata } as Metadata;\n if (metadataClone['contentType'] == null && data.contentType != null) {\n metadataClone['contentType'] = data.contentType!;\n }\n return uploadBytes(ref, data.data, metadataClone);\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 * @public\n * @param ref - StorageReference to get list from.\n *\n * @returns 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 */\nexport function listAll(ref: Reference): Promise<ListResult> {\n const accumulator: ListResult = {\n prefixes: [],\n items: []\n };\n return listAllHelper(ref, accumulator).then(() => accumulator);\n}\n\n/**\n * Separated from listAll because async functions can't use \"arguments\".\n * @param ref\n * @param accumulator\n * @param pageToken\n */\nasync function listAllHelper(\n ref: Reference,\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 list(ref, opt);\n accumulator.prefixes.push(...nextPage.prefixes);\n accumulator.items.push(...nextPage.items);\n if (nextPage.nextPageToken != null) {\n await listAllHelper(ref, 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 * @public\n *\n * @param ref - StorageReference to get list from.\n * @param options - See ListOptions for details.\n * @returns 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 */\nexport function list(\n ref: Reference,\n options?: ListOptions | null\n): Promise<ListResult> {\n if (options != null) {\n if (typeof options.maxResults === 'number') {\n validateNumber(\n 'options.maxResults',\n /* minValue= */ 1,\n /* maxValue= */ 1000,\n options.maxResults\n );\n }\n }\n const op = options || {};\n const requestInfo = requestsList(\n ref.storage,\n ref._location,\n /*delimiter= */ '/',\n op.pageToken,\n op.maxResults\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\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 * @public\n * @param ref - StorageReference to get metadata from.\n */\nexport function getMetadata(ref: Reference): Promise<Metadata> {\n ref._throwIfRoot('getMetadata');\n const requestInfo = requestsGetMetadata(\n ref.storage,\n ref._location,\n getMappings()\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Updates the metadata for this object.\n * @public\n * @param ref - StorageReference to update metadata for.\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 * @returns A `Promise` that resolves\n * with the new metadata for this object.\n * See `firebaseStorage.Reference.prototype.getMetadata`\n */\nexport function updateMetadata(\n ref: Reference,\n metadata: Partial<Metadata>\n): Promise<Metadata> {\n ref._throwIfRoot('updateMetadata');\n const requestInfo = requestsUpdateMetadata(\n ref.storage,\n ref._location,\n metadata,\n getMappings()\n );\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Returns the download URL for the given Reference.\n * @public\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\nexport function getDownloadURL(ref: Reference): Promise<string> {\n ref._throwIfRoot('getDownloadURL');\n const requestInfo = requestsGetDownloadUrl(\n ref.storage,\n ref._location,\n getMappings()\n );\n return ref.storage\n .makeRequestWithTokens(requestInfo, newTextConnection)\n .then(url => {\n if (url === null) {\n throw noDownloadURL();\n }\n return url;\n });\n}\n\n/**\n * Deletes the object at this location.\n * @public\n * @param ref - StorageReference for object to delete.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\nexport function deleteObject(ref: Reference): Promise<void> {\n ref._throwIfRoot('deleteObject');\n const requestInfo = requestsDeleteObject(ref.storage, ref._location);\n return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);\n}\n\n/**\n * Returns reference for object obtained by appending `childPath` to `ref`.\n *\n * @param ref - StorageReference to get child of.\n * @param childPath - Child path from provided ref.\n * @returns A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n *\n */\nexport function _getChild(ref: Reference, childPath: string): Reference {\n const newPath = child(ref._location.path, childPath);\n const location = new Location(ref._location.bucket, newPath);\n return new Reference(ref.storage, location);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Location } from './implementation/location';\nimport { FailRequest } from './implementation/failrequest';\nimport { Request, makeRequest } from './implementation/request';\nimport { RequestInfo } from './implementation/requestinfo';\nimport { Reference, _getChild } from './reference';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\nimport {\n CONFIG_STORAGE_BUCKET_KEY,\n DEFAULT_HOST,\n DEFAULT_MAX_OPERATION_RETRY_TIME,\n DEFAULT_MAX_UPLOAD_RETRY_TIME\n} from './implementation/constants';\nimport {\n invalidArgument,\n appDeleted,\n noDefaultBucket\n} from './implementation/error';\nimport { validateNumber } from './implementation/type';\nimport { FirebaseStorage } from './public-types';\nimport { createMockUserToken, EmulatorMockTokenOptions } from '@firebase/util';\nimport { Connection, ConnectionType } from './implementation/connection';\n\nexport function isUrl(path?: string): boolean {\n return /^[A-Za-z]+:\\/\\//.test(path as string);\n}\n\n/**\n * Returns a firebaseStorage.Reference for the given url.\n */\nfunction refFromURL(service: FirebaseStorageImpl, url: string): Reference {\n return new Reference(service, url);\n}\n\n/**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\nfunction refFromPath(\n ref: FirebaseStorageImpl | Reference,\n path?: string\n): Reference {\n if (ref instanceof FirebaseStorageImpl) {\n const service = ref;\n if (service._bucket == null) {\n throw noDefaultBucket();\n }\n const reference = new Reference(service, service._bucket!);\n if (path != null) {\n return refFromPath(reference, path);\n } else {\n return reference;\n }\n } else {\n // ref is a Reference\n if (path !== undefined) {\n return _getChild(ref, path);\n } else {\n return ref;\n }\n }\n}\n\n/**\n * Returns a storage Reference for the given url.\n * @param storage - `Storage` instance.\n * @param url - URL. If empty, returns root reference.\n * @public\n */\nexport function ref(storage: FirebaseStorageImpl, url?: string): Reference;\n/**\n * Returns a storage Reference for the given path in the\n * default bucket.\n * @param storageOrRef - `Storage` service or storage `Reference`.\n * @param pathOrUrlStorage - path. If empty, returns root reference (if Storage\n * instance provided) or returns same reference (if Reference provided).\n * @public\n */\nexport function ref(\n storageOrRef: FirebaseStorageImpl | Reference,\n path?: string\n): Reference;\nexport function ref(\n serviceOrRef: FirebaseStorageImpl | Reference,\n pathOrUrl?: string\n): Reference | null {\n if (pathOrUrl && isUrl(pathOrUrl)) {\n if (serviceOrRef instanceof FirebaseStorageImpl) {\n return refFromURL(serviceOrRef, pathOrUrl);\n } else {\n throw invalidArgument(\n 'To use ref(service, url), the first argument must be a Storage instance.'\n );\n }\n } else {\n return refFromPath(serviceOrRef, pathOrUrl);\n }\n}\n\nfunction extractBucket(\n host: string,\n config?: FirebaseOptions\n): Location | null {\n const bucketString = config?.[CONFIG_STORAGE_BUCKET_KEY];\n if (bucketString == null) {\n return null;\n }\n return Location.makeFromBucketSpec(bucketString, host);\n}\n\nexport function connectStorageEmulator(\n storage: FirebaseStorageImpl,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n storage.host = `${host}:${port}`;\n storage._protocol = 'http';\n const { mockUserToken } = options;\n if (mockUserToken) {\n storage._overrideAuthToken =\n typeof mockUserToken === 'string'\n ? mockUserToken\n : createMockUserToken(mockUserToken, storage.app.options.projectId);\n }\n}\n\n/**\n * A service that provides Firebase Storage Reference instances.\n * @param opt_url - gs:// url to a custom Storage Bucket\n *\n * @internal\n */\nexport class FirebaseStorageImpl implements FirebaseStorage {\n _bucket: Location | null = null;\n /**\n * This string can be in the formats:\n * - host\n * - host:port\n */\n private _host: string = DEFAULT_HOST;\n _protocol: string = 'https';\n protected readonly _appId: string | null = null;\n private readonly _requests: Set<Request<unknown>>;\n private _deleted: boolean = false;\n private _maxOperationRetryTime: number;\n private _maxUploadRetryTime: number;\n _overrideAuthToken?: string;\n\n constructor(\n /**\n * FirebaseApp associated with this StorageService instance.\n */\n readonly app: FirebaseApp,\n readonly _authProvider: Provider<FirebaseAuthInternalName>,\n /**\n * @internal\n */\n readonly _appCheckProvider: Provider<AppCheckInternalComponentName>,\n /**\n * @internal\n */\n readonly _url?: string,\n readonly _firebaseVersion?: string\n ) {\n this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;\n this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;\n this._requests = new Set();\n if (_url != null) {\n this._bucket = Location.makeFromBucketSpec(_url, this._host);\n } else {\n this._bucket = extractBucket(this._host, this.app.options);\n }\n }\n\n /**\n * The host string for this service, in the form of `host` or\n * `host:port`.\n */\n get host(): string {\n return this._host;\n }\n\n set host(host: string) {\n this._host = host;\n if (this._url != null) {\n this._bucket = Location.makeFromBucketSpec(this._url, host);\n } else {\n this._bucket = extractBucket(host, this.app.options);\n }\n }\n\n /**\n * The maximum time to retry uploads in milliseconds.\n */\n get maxUploadRetryTime(): number {\n return this._maxUploadRetryTime;\n }\n\n set maxUploadRetryTime(time: number) {\n validateNumber(\n 'time',\n /* minValue=*/ 0,\n /* maxValue= */ Number.POSITIVE_INFINITY,\n time\n );\n this._maxUploadRetryTime = time;\n }\n\n /**\n * The maximum time to retry operations other than uploads or downloads in\n * milliseconds.\n */\n get maxOperationRetryTime(): number {\n return this._maxOperationRetryTime;\n }\n\n set maxOperationRetryTime(time: number) {\n validateNumber(\n 'time',\n /* minValue=*/ 0,\n /* maxValue= */ Number.POSITIVE_INFINITY,\n time\n );\n this._maxOperationRetryTime = time;\n }\n\n async _getAuthToken(): Promise<string | null> {\n if (this._overrideAuthToken) {\n return this._overrideAuthToken;\n }\n const auth = this._authProvider.getImmediate({ optional: true });\n if (auth) {\n const tokenData = await auth.getToken();\n if (tokenData !== null) {\n return tokenData.accessToken;\n }\n }\n return null;\n }\n\n async _getAppCheckToken(): Promise<string | null> {\n const appCheck = this._appCheckProvider.getImmediate({ optional: true });\n if (appCheck) {\n const result = await appCheck.getToken();\n // TODO: What do we want to do if there is an error getting the token?\n // Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be\n // returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n return result.token;\n }\n return null;\n }\n\n /**\n * Stop running requests and prevent more from being created.\n */\n _delete(): Promise<void> {\n if (!this._deleted) {\n this._deleted = true;\n this._requests.forEach(request => request.cancel());\n this._requests.clear();\n }\n return Promise.resolve();\n }\n\n /**\n * Returns a new firebaseStorage.Reference object referencing this StorageService\n * at the given Location.\n */\n _makeStorageReference(loc: Location): Reference {\n return new Reference(this, loc);\n }\n\n /**\n * @param requestInfo - HTTP RequestInfo object\n * @param authToken - Firebase auth token\n */\n _makeRequest<I extends ConnectionType, O>(\n requestInfo: RequestInfo<I, O>,\n requestFactory: () => Connection<I>,\n authToken: string | null,\n appCheckToken: string | null,\n retry = true\n ): Request<O> {\n if (!this._deleted) {\n const request = makeRequest(\n requestInfo,\n this._appId,\n authToken,\n appCheckToken,\n requestFactory,\n this._firebaseVersion,\n retry\n );\n this._requests.add(request);\n // Request removes itself from set when complete.\n request.getPromise().then(\n () => this._requests.delete(request),\n () => this._requests.delete(request)\n );\n return request;\n } else {\n return new FailRequest(appDeleted());\n }\n }\n\n async makeRequestWithTokens<I extends ConnectionType, O>(\n requestInfo: RequestInfo<I, O>,\n requestFactory: () => Connection<I>\n ): Promise<O> {\n const [authToken, appCheckToken] = await Promise.all([\n this._getAuthToken(),\n this._getAppCheckToken()\n ]);\n\n return this._makeRequest(\n requestInfo,\n requestFactory,\n authToken,\n appCheckToken\n ).getPromise();\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\n\nimport {\n ref as refInternal,\n FirebaseStorageImpl,\n connectStorageEmulator as connectEmulatorInternal\n} from './service';\nimport { Provider } from '@firebase/component';\n\nimport {\n StorageReference,\n FirebaseStorage,\n UploadResult,\n ListOptions,\n ListResult,\n UploadTask,\n SettableMetadata,\n UploadMetadata,\n FullMetadata\n} from './public-types';\nimport { Metadata as MetadataInternal } from './metadata';\nimport {\n uploadBytes as uploadBytesInternal,\n uploadBytesResumable as uploadBytesResumableInternal,\n uploadString as uploadStringInternal,\n getMetadata as getMetadataInternal,\n updateMetadata as updateMetadataInternal,\n list as listInternal,\n listAll as listAllInternal,\n getDownloadURL as getDownloadURLInternal,\n deleteObject as deleteObjectInternal,\n Reference,\n _getChild as _getChildInternal,\n getBytesInternal\n} from './reference';\nimport { STORAGE_TYPE } from './constants';\nimport {\n EmulatorMockTokenOptions,\n getModularInstance,\n getDefaultEmulatorHostnameAndPort\n} from '@firebase/util';\nimport { StringFormat } from './implementation/string';\n\nexport { EmulatorMockTokenOptions } from '@firebase/util';\n\nexport { StorageError, StorageErrorCode } from './implementation/error';\n\n/**\n * Public types.\n */\nexport * from './public-types';\n\nexport { Location as _Location } from './implementation/location';\nexport { UploadTask as _UploadTask } from './task';\nexport type { Reference as _Reference } from './reference';\nexport type { FirebaseStorageImpl as _FirebaseStorageImpl } from './service';\nexport { FbsBlob as _FbsBlob } from './implementation/blob';\nexport { dataFromString as _dataFromString } from './implementation/string';\nexport {\n invalidRootOperation as _invalidRootOperation,\n invalidArgument as _invalidArgument\n} from './implementation/error';\nexport {\n TaskEvent as _TaskEvent,\n TaskState as _TaskState\n} from './implementation/taskenums';\nexport { StringFormat };\n\n/**\n * Downloads the data at the object's location. Returns an error if the object\n * is not found.\n *\n * To use this functionality, you have to whitelist your app's origin in your\n * Cloud Storage bucket. See also\n * https://cloud.google.com/storage/docs/configuring-cors\n *\n * @public\n * @param ref - StorageReference where data should be downloaded.\n * @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to\n * retrieve.\n * @returns A Promise containing the object's bytes\n */\nexport function getBytes(\n ref: StorageReference,\n maxDownloadSizeBytes?: number\n): Promise<ArrayBuffer> {\n ref = getModularInstance(ref);\n return getBytesInternal(ref as Reference, maxDownloadSizeBytes);\n}\n\n/**\n * Uploads data to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - {@link StorageReference} where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the data to upload.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadBytes(\n ref: StorageReference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: UploadMetadata\n): Promise<UploadResult> {\n ref = getModularInstance(ref);\n return uploadBytesInternal(\n ref as Reference,\n data,\n metadata as MetadataInternal\n );\n}\n\n/**\n * Uploads a string to this object's location.\n * The upload is not resumable.\n * @public\n * @param ref - {@link StorageReference} where string should be uploaded.\n * @param value - The string to upload.\n * @param format - The format of the string to upload.\n * @param metadata - Metadata for the string to upload.\n * @returns A Promise containing an UploadResult\n */\nexport function uploadString(\n ref: StorageReference,\n value: string,\n format?: StringFormat,\n metadata?: UploadMetadata\n): Promise<UploadResult> {\n ref = getModularInstance(ref);\n return uploadStringInternal(\n ref as Reference,\n value,\n format,\n metadata as MetadataInternal\n );\n}\n\n/**\n * Uploads data to this object's location.\n * The upload can be paused and resumed, and exposes progress updates.\n * @public\n * @param ref - {@link StorageReference} where data should be uploaded.\n * @param data - The data to upload.\n * @param metadata - Metadata for the data to upload.\n * @returns An UploadTask\n */\nexport function uploadBytesResumable(\n ref: StorageReference,\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: UploadMetadata\n): UploadTask {\n ref = getModularInstance(ref);\n return uploadBytesResumableInternal(\n ref as Reference,\n data,\n metadata as MetadataInternal\n ) as UploadTask;\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 * @public\n * @param ref - {@link StorageReference} to get metadata from.\n */\nexport function getMetadata(ref: StorageReference): Promise<FullMetadata> {\n ref = getModularInstance(ref);\n return getMetadataInternal(ref as Reference) as Promise<FullMetadata>;\n}\n\n/**\n * Updates the metadata for this object.\n * @public\n * @param ref - {@link StorageReference} to update metadata for.\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 * @returns A `Promise` that resolves with the new metadata for this object.\n */\nexport function updateMetadata(\n ref: StorageReference,\n metadata: SettableMetadata\n): Promise<FullMetadata> {\n ref = getModularInstance(ref);\n return updateMetadataInternal(\n ref as Reference,\n metadata as Partial<MetadataInternal>\n ) as Promise<FullMetadata>;\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 * @public\n *\n * @param ref - {@link StorageReference} to get list from.\n * @param options - See {@link ListOptions} for details.\n * @returns 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 */\nexport function list(\n ref: StorageReference,\n options?: ListOptions\n): Promise<ListResult> {\n ref = getModularInstance(ref);\n return listInternal(ref as Reference, options);\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 * @public\n * @param ref - {@link StorageReference} to get list from.\n *\n * @returns 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 */\nexport function listAll(ref: StorageReference): Promise<ListResult> {\n ref = getModularInstance(ref);\n return listAllInternal(ref as Reference);\n}\n\n/**\n * Returns the download URL for the given {@link StorageReference}.\n * @public\n * @param ref - {@link StorageReference} to get the download URL for.\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\nexport function getDownloadURL(ref: StorageReference): Promise<string> {\n ref = getModularInstance(ref);\n return getDownloadURLInternal(ref as Reference);\n}\n\n/**\n * Deletes the object at this location.\n * @public\n * @param ref - {@link StorageReference} for object to delete.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\nexport function deleteObject(ref: StorageReference): Promise<void> {\n ref = getModularInstance(ref);\n return deleteObjectInternal(ref as Reference);\n}\n\n/**\n * Returns a {@link StorageReference} for the given url.\n * @param storage - {@link FirebaseStorage} instance.\n * @param url - URL. If empty, returns root reference.\n * @public\n */\nexport function ref(storage: FirebaseStorage, url?: string): StorageReference;\n/**\n * Returns a {@link StorageReference} for the given path in the\n * default bucket.\n * @param storageOrRef - {@link FirebaseStorage} or {@link StorageReference}.\n * @param pathOrUrlStorage - path. If empty, returns root reference (if {@link FirebaseStorage}\n * instance provided) or returns same reference (if {@link StorageReference} provided).\n * @public\n */\nexport function ref(\n storageOrRef: FirebaseStorage | StorageReference,\n path?: string\n): StorageReference;\nexport function ref(\n serviceOrRef: FirebaseStorage | StorageReference,\n pathOrUrl?: string\n): StorageReference | null {\n serviceOrRef = getModularInstance(serviceOrRef);\n return refInternal(\n serviceOrRef as FirebaseStorageImpl | Reference,\n pathOrUrl\n );\n}\n\n/**\n * @internal\n */\nexport function _getChild(ref: StorageReference, childPath: string): Reference {\n return _getChildInternal(ref as Reference, childPath);\n}\n\n/**\n * Gets a {@link FirebaseStorage} instance for the given Firebase app.\n * @public\n * @param app - Firebase app to get {@link FirebaseStorage} instance for.\n * @param bucketUrl - The gs:// url to your Firebase Storage Bucket.\n * If not passed, uses the app's default Storage Bucket.\n * @returns A {@link FirebaseStorage} instance.\n */\nexport function getStorage(\n app: FirebaseApp = getApp(),\n bucketUrl?: string\n): FirebaseStorage {\n app = getModularInstance(app);\n const storageProvider: Provider<'storage'> = _getProvider(app, STORAGE_TYPE);\n const storageInstance = storageProvider.getImmediate({\n identifier: bucketUrl\n });\n const emulator = getDefaultEmulatorHostnameAndPort('storage');\n if (emulator) {\n connectStorageEmulator(storageInstance, ...emulator);\n }\n return storageInstance;\n}\n\n/**\n * Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.\n *\n * @param storage - The {@link FirebaseStorage} instance\n * @param host - The emulator host (ex: localhost)\n * @param port - The emulator port (ex: 5001)\n * @param options - Emulator options. `options.mockUserToken` is the mock auth\n * token to use for unit testing Security Rules.\n * @public\n */\nexport function connectStorageEmulator(\n storage: FirebaseStorage,\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n): void {\n connectEmulatorInternal(storage as FirebaseStorageImpl, host, port, options);\n}\n","/**\n * Cloud Storage for Firebase\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\n\nimport { FirebaseStorageImpl } from '../src/service';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\nimport { FirebaseStorage } from './public-types';\nimport { STORAGE_TYPE } from './constants';\n\nexport * from './api';\nexport * from './api.browser';\n\nfunction factory(\n container: ComponentContainer,\n { instanceIdentifier: url }: InstanceFactoryOptions\n): FirebaseStorage {\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n\n return new FirebaseStorageImpl(\n app,\n authProvider,\n appCheckProvider,\n url,\n SDK_VERSION\n );\n}\n\nfunction registerStorage(): void {\n _registerComponent(\n new Component(\n STORAGE_TYPE,\n factory,\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n //RUNTIME_ENV will be replaced during the compilation to \"node\" for nodejs and an empty string for browser\n registerVersion(name, version, '__RUNTIME_ENV__');\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\nregisterStorage();\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Type constant for Firebase Storage.\n */\nexport const STORAGE_TYPE = 'storage';\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UploadTaskSnapshot } from '@firebase/storage';\nimport { ReferenceCompat } from './reference';\nimport { UploadTaskCompat } from './task';\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class UploadTaskSnapshotCompat\n implements types.UploadTaskSnapshot, Compat<UploadTaskSnapshot>\n{\n constructor(\n readonly _delegate: UploadTaskSnapshot,\n readonly task: UploadTaskCompat,\n readonly ref: ReferenceCompat\n ) {}\n\n get bytesTransferred(): number {\n return this._delegate.bytesTransferred;\n }\n get metadata(): types.FullMetadata {\n return this._delegate.metadata as types.FullMetadata;\n }\n get state(): string {\n return this._delegate.state;\n }\n get totalBytes(): number {\n return this._delegate.totalBytes;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n UploadTask,\n StorageError,\n UploadTaskSnapshot,\n TaskEvent,\n StorageObserver\n} from '@firebase/storage';\nimport { UploadTaskSnapshotCompat } from './tasksnapshot';\nimport { ReferenceCompat } from './reference';\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class UploadTaskCompat implements types.UploadTask, Compat<UploadTask> {\n constructor(\n readonly _delegate: UploadTask,\n private readonly _ref: ReferenceCompat\n ) {}\n\n get snapshot(): UploadTaskSnapshotCompat {\n return new UploadTaskSnapshotCompat(\n this._delegate.snapshot,\n this,\n this._ref\n );\n }\n\n cancel = this._delegate.cancel.bind(this._delegate);\n catch = this._delegate.catch.bind(this._delegate);\n pause = this._delegate.pause.bind(this._delegate);\n resume = this._delegate.resume.bind(this._delegate);\n\n then(\n onFulfilled?: ((a: UploadTaskSnapshotCompat) => unknown) | null,\n onRejected?: ((a: StorageError) => unknown) | null\n ): Promise<unknown> {\n return this._delegate.then(snapshot => {\n if (onFulfilled) {\n return onFulfilled(\n new UploadTaskSnapshotCompat(snapshot, this, this._ref)\n );\n }\n }, onRejected);\n }\n\n on(\n type: TaskEvent,\n nextOrObserver?:\n | types.StorageObserver<UploadTaskSnapshotCompat>\n | null\n | ((a: UploadTaskSnapshotCompat) => unknown),\n error?: ((error: StorageError) => void) | null,\n completed?: () => void | null\n ): Unsubscribe | Subscribe<UploadTaskSnapshotCompat> {\n let wrappedNextOrObserver:\n | StorageObserver<UploadTaskSnapshot>\n | undefined\n | ((a: UploadTaskSnapshot) => unknown) = undefined;\n if (!!nextOrObserver) {\n if (typeof nextOrObserver === 'function') {\n wrappedNextOrObserver = (taskSnapshot: UploadTaskSnapshot) =>\n nextOrObserver(\n new UploadTaskSnapshotCompat(taskSnapshot, this, this._ref)\n );\n } else {\n wrappedNextOrObserver = {\n next: !!nextOrObserver.next\n ? (taskSnapshot: UploadTaskSnapshot) =>\n nextOrObserver.next!(\n new UploadTaskSnapshotCompat(taskSnapshot, this, this._ref)\n )\n : undefined,\n complete: nextOrObserver.complete || undefined,\n error: nextOrObserver.error || undefined\n };\n }\n }\n return this._delegate.on(\n type,\n wrappedNextOrObserver,\n error || undefined,\n completed || undefined\n );\n }\n}\n\n/**\n * Subscribes to an event stream.\n */\nexport type Subscribe<T> = (\n next?: NextFn<T> | StorageObserver<T>,\n error?: ErrorFn,\n complete?: CompleteFn\n) => Unsubscribe;\n\n/**\n * Unsubscribes from a stream.\n */\nexport type Unsubscribe = () => void;\n\n/**\n * Function that is called once for each value in a stream of values.\n */\nexport type NextFn<T> = (value: T) => void;\n\n/**\n * A function that is called with a `FirebaseStorageError`\n * if the event stream ends due to an error.\n */\nexport type ErrorFn = (error: StorageError) => void;\n\n/**\n * A function that is called if the event stream ends normally.\n */\nexport type CompleteFn = () => void;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ListResult } from '@firebase/storage';\nimport * as types from '@firebase/storage-types';\nimport { ReferenceCompat } from './reference';\nimport { StorageServiceCompat } from './service';\nimport { Compat } from '@firebase/util';\n\nexport class ListResultCompat implements types.ListResult, Compat<ListResult> {\n constructor(\n readonly _delegate: ListResult,\n private readonly _service: StorageServiceCompat\n ) {}\n\n get prefixes(): ReferenceCompat[] {\n return this._delegate.prefixes.map(\n ref => new ReferenceCompat(ref, this._service)\n );\n }\n get items(): ReferenceCompat[] {\n return this._delegate.items.map(\n ref => new ReferenceCompat(ref, this._service)\n );\n }\n get nextPageToken(): string | null {\n return this._delegate.nextPageToken || null;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n StorageReference,\n uploadBytesResumable,\n list,\n listAll,\n getDownloadURL,\n getMetadata,\n updateMetadata,\n deleteObject,\n UploadTask,\n StringFormat,\n UploadMetadata,\n FullMetadata,\n SettableMetadata,\n _UploadTask,\n _getChild,\n _Reference,\n _FbsBlob,\n _dataFromString,\n _invalidRootOperation\n} from '@firebase/storage';\n\nimport { UploadTaskCompat } from './task';\nimport { ListResultCompat } from './list';\nimport { StorageServiceCompat } from './service';\n\nimport * as types from '@firebase/storage-types';\nimport { Compat } from '@firebase/util';\n\nexport class ReferenceCompat\n implements types.Reference, Compat<StorageReference>\n{\n constructor(\n readonly _delegate: StorageReference,\n public storage: StorageServiceCompat\n ) {}\n\n get name(): string {\n return this._delegate.name;\n }\n\n get bucket(): string {\n return this._delegate.bucket;\n }\n\n get fullPath(): string {\n return this._delegate.fullPath;\n }\n\n toString(): string {\n return this._delegate.toString();\n }\n\n /**\n * @returns A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n child(childPath: string): types.Reference {\n const reference = _getChild(this._delegate, childPath);\n return new ReferenceCompat(reference, this.storage);\n }\n\n get root(): types.Reference {\n return new ReferenceCompat(this._delegate.root, this.storage);\n }\n\n /**\n * @returns A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get parent(): types.Reference | null {\n const reference = this._delegate.parent;\n if (reference == null) {\n return null;\n }\n return new ReferenceCompat(reference, this.storage);\n }\n\n /**\n * Uploads a blob to this object's location.\n * @param data - The blob to upload.\n * @returns An UploadTask that lets you control and\n * observe the upload.\n */\n put(\n data: Blob | Uint8Array | ArrayBuffer,\n metadata?: types.FullMetadata\n ): types.UploadTask {\n this._throwIfRoot('put');\n return new UploadTaskCompat(\n uploadBytesResumable(this._delegate, data, metadata as UploadMetadata),\n this\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 * @returns An UploadTask that lets you control and\n * observe the upload.\n */\n putString(\n value: string,\n format: StringFormat = StringFormat.RAW,\n metadata?: types.UploadMetadata\n ): types.UploadTask {\n this._throwIfRoot('putString');\n const data = _dataFromString(format, value);\n const metadataClone = { ...metadata };\n if (metadataClone['contentType'] == null && data.contentType != null) {\n metadataClone['contentType'] = data.contentType;\n }\n return new UploadTaskCompat(\n new _UploadTask(\n this._delegate as _Reference,\n new _FbsBlob(data.data, true),\n metadataClone as FullMetadata & { [k: string]: string }\n ) as UploadTask,\n this\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 * @returns 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<types.ListResult> {\n return listAll(this._delegate).then(\n r => new ListResultCompat(r, this.storage)\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. 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 * @returns 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?: types.ListOptions | null): Promise<types.ListResult> {\n return list(this._delegate, options || undefined).then(\n r => new ListResultCompat(r, this.storage)\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<types.FullMetadata> {\n return getMetadata(this._delegate) as Promise<types.FullMetadata>;\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 * @returns A `Promise` that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n updateMetadata(\n metadata: types.SettableMetadata\n ): Promise<types.FullMetadata> {\n return updateMetadata(\n this._delegate,\n metadata as SettableMetadata\n ) as Promise<types.FullMetadata>;\n }\n\n /**\n * @returns A `Promise` that resolves with the download\n * URL for this object.\n */\n getDownloadURL(): Promise<string> {\n return getDownloadURL(this._delegate);\n }\n\n /**\n * Deletes the object at this location.\n * @returns A `Promise` that resolves if the deletion succeeds.\n */\n delete(): Promise<void> {\n this._throwIfRoot('delete');\n return deleteObject(this._delegate);\n }\n\n private _throwIfRoot(name: string): void {\n if ((this._delegate as _Reference)._location.path === '') {\n throw _invalidRootOperation(name);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as types from '@firebase/storage-types';\nimport { FirebaseApp } from '@firebase/app-types';\n\nimport {\n ref,\n connectStorageEmulator,\n FirebaseStorage,\n _Location,\n _invalidArgument,\n _FirebaseStorageImpl\n} from '@firebase/storage';\nimport { ReferenceCompat } from './reference';\nimport { Compat, EmulatorMockTokenOptions } from '@firebase/util';\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n */\nexport class StorageServiceCompat\n implements types.FirebaseStorage, Compat<FirebaseStorage>\n{\n constructor(public app: FirebaseApp, readonly _delegate: FirebaseStorage) {}\n\n get maxOperationRetryTime(): number {\n return this._delegate.maxOperationRetryTime;\n }\n\n get maxUploadRetryTime(): number {\n return this._delegate.maxUploadRetryTime;\n }\n\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n ref(path?: string): types.Reference {\n if (isUrl(path)) {\n throw _invalidArgument(\n 'ref() expected a child path but got a URL, use refFromURL instead.'\n );\n }\n return new ReferenceCompat(ref(this._delegate, path), this);\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): types.Reference {\n if (!isUrl(url)) {\n throw _invalidArgument(\n 'refFromURL() expected a full URL but got a child path, use ref() instead.'\n );\n }\n try {\n _Location.makeFromUrl(url, (this._delegate as _FirebaseStorageImpl).host);\n } catch (e) {\n throw _invalidArgument(\n 'refFromUrl() expected a valid full URL but got an invalid one.'\n );\n }\n return new ReferenceCompat(ref(this._delegate, url), this);\n }\n\n setMaxUploadRetryTime(time: number): void {\n this._delegate.maxUploadRetryTime = time;\n }\n\n setMaxOperationRetryTime(time: number): void {\n this._delegate.maxOperationRetryTime = time;\n }\n\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n ): void {\n connectStorageEmulator(this._delegate, host, port, options);\n }\n}\n\nfunction isUrl(path?: string): boolean {\n return /^[A-Za-z]+:\\/\\//.test(path as string);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 NetworkInformationWithEffectiveType extends NetworkInformation {\n // `effectiveType` is an experimental property and not included in\n // TypeScript's typings for the native NetworkInformation interface\n readonly effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';\n}\n\ninterface NavigatorWithConnection extends Navigator {\n readonly connection: NetworkInformationWithEffectiveType;\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 (navigator?.serviceWorker) {\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport {\n Component,\n ComponentContainer,\n ComponentType\n} from '@firebase/component';\nimport { PerformanceCompatImpl } from './performance';\nimport { name as packageName, version } from '../package.json';\nimport { FirebasePerformance as FirebasePerformanceCompat } from '@firebase/performance-types';\n\nfunction registerPerformanceCompat(firebaseInstance: _FirebaseNamespace): void {\n firebaseInstance.INTERNAL.registerComponent(\n new Component(\n 'performance-compat',\n performanceFactory,\n ComponentType.PUBLIC\n )\n );\n\n firebaseInstance.registerVersion(packageName, version);\n}\n\nfunction performanceFactory(\n container: ComponentContainer\n): PerformanceCompatImpl {\n const app = container.getProvider('app-compat').getImmediate();\n // The following call will always succeed.\n const performance = container.getProvider('performance').getImmediate();\n\n return new PerformanceCompatImpl(app, performance);\n}\n\nregisterPerformanceCompat(firebase as _FirebaseNamespace);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n performance: {\n (app?: FirebaseApp): FirebasePerformanceCompat;\n };\n }\n interface FirebaseApp {\n performance(): FirebasePerformanceCompat;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport {\n Component,\n ComponentContainer,\n ComponentType,\n InstanceFactoryOptions\n} from '@firebase/component';\nimport { RemoteConfigCompatImpl, isSupported } from './remoteConfig';\nimport { name as packageName, version } from '../package.json';\nimport { RemoteConfig as RemoteConfigCompat } from '@firebase/remote-config-types';\n\nfunction registerRemoteConfigCompat(\n firebaseInstance: _FirebaseNamespace\n): void {\n firebaseInstance.INTERNAL.registerComponent(\n new Component(\n 'remoteConfig-compat',\n remoteConfigFactory,\n ComponentType.PUBLIC\n )\n .setMultipleInstances(true)\n .setServiceProps({ isSupported })\n );\n\n firebaseInstance.registerVersion(packageName, version);\n}\n\nfunction remoteConfigFactory(\n container: ComponentContainer,\n { instanceIdentifier: namespace }: InstanceFactoryOptions\n): RemoteConfigCompatImpl {\n const app = container.getProvider('app-compat').getImmediate();\n // The following call will always succeed because rc `import {...} from '@firebase/remote-config'`\n const remoteConfig = container.getProvider('remote-config').getImmediate({\n identifier: namespace\n });\n\n return new RemoteConfigCompatImpl(app, remoteConfig);\n}\n\nregisterRemoteConfigCompat(firebase as _FirebaseNamespace);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n remoteConfig: {\n (app?: FirebaseApp): RemoteConfigCompat;\n };\n }\n interface FirebaseApp {\n remoteConfig(): RemoteConfigCompat;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 NONPOSITIVE_TRACE_START_TIME = 'nonpositive trace startTime',\n NONPOSITIVE_TRACE_DURATION = 'nonpositive trace duration',\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 = 'invalid custom metric name',\n INVALID_STRING_MERGER_PARAMETER = 'invalid String merger input',\n ALREADY_INITIALIZED = 'already initialized'\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.NONPOSITIVE_TRACE_START_TIME]:\n 'Trace {$traceName} startTime should be positive.',\n [ErrorCode.NONPOSITIVE_TRACE_DURATION]:\n 'Trace {$traceName} duration should be positive.',\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 [ErrorCode.INVALID_STRING_MERGER_PARAMETER]:\n 'Input for String merger is invalid, contact support team to resolve.',\n [ErrorCode.ALREADY_INITIALIZED]:\n 'initializePerformance() has already been called with ' +\n 'different options. To avoid this error, call initializePerformance() with the ' +\n 'same options as when it was originally called, or call getPerformance() to return the' +\n ' already initialized instance.'\n};\n\ninterface ErrorParams {\n [ErrorCode.TRACE_STARTED_BEFORE]: { traceName: string };\n [ErrorCode.TRACE_STOPPED_BEFORE]: { traceName: string };\n [ErrorCode.NONPOSITIVE_TRACE_START_TIME]: { traceName: string };\n [ErrorCode.NONPOSITIVE_TRACE_DURATION]: { 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\nimport { isIndexedDBAvailable, areCookiesEnabled } from '@firebase/util';\nimport { consoleLogger } from '../utils/console_logger';\n\ndeclare global {\n interface Window {\n PerformanceObserver: typeof PerformanceObserver;\n perfMetrics?: { onFirstInputDelay(fn: (fid: number) => void): void };\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?: (fn: (fid: number) => void) => void;\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 || !areCookiesEnabled()) {\n consoleLogger.info(\n 'Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled.'\n );\n return false;\n }\n\n if (!isIndexedDBAvailable()) {\n consoleLogger.info('IndexedDB is not supported by current browser');\n return false;\n }\n return true;\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\n\nlet iid: string | undefined;\nlet authToken: string | undefined;\n\nexport function getIidPromise(\n installationsService: _FirebaseInstallationsInternal\n): Promise<string> {\n const iidPromise = 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(\n installationsService: _FirebaseInstallationsInternal\n): Promise<string> {\n const authTokenPromise = 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from './errors';\n\nexport function mergeStrings(part1: string, part2: string): string {\n const sizeDiff = part1.length - part2.length;\n if (sizeDiff < 0 || sizeDiff > 1) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_STRING_MERGER_PARAMETER);\n }\n\n const resultArray = [];\n for (let i = 0; i < part1.length; i++) {\n resultArray.push(part1.charAt(i));\n if (part2.length > i) {\n resultArray.push(part2.charAt(i));\n }\n }\n\n return resultArray.join('');\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { mergeStrings } from '../utils/string_merger';\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\n // Address of logging service.\n logEndPointUrl =\n 'https://firebaselogging.googleapis.com/v0cc/log?format=json_proto';\n // Performance event transport endpoint URL which should be compatible with proto3.\n // New Address for transport service, not configurable via Remote Config.\n flTransportEndpointUrl = mergeStrings(\n 'hts/frbslgigp.ogepscmv/ieo/eaylg',\n 'tp:/ieaeogn-agolai.o/1frlglgc/o'\n );\n\n transportKey = mergeStrings('AzSC8r6ReiGqFMyfvgow', 'Iayx0u-XT3vksVM-pIV');\n\n // Source type for performance event logs.\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 getFlTransportFullUrl(): string {\n return this.flTransportEndpointUrl.concat('?key=', this.transportKey);\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ERROR_FACTORY, ErrorCode } from './errors';\nimport { FirebaseApp } from '@firebase/app';\n\nexport function getAppId(firebaseApp: FirebaseApp): string {\n const appId = firebaseApp.options?.appId;\n if (!appId) {\n throw ERROR_FACTORY.create(ErrorCode.NO_APP_ID);\n }\n return appId;\n}\n\nexport function getProjectId(firebaseApp: FirebaseApp): string {\n const projectId = firebaseApp.options?.projectId;\n if (!projectId) {\n throw ERROR_FACTORY.create(ErrorCode.NO_PROJECT_ID);\n }\n return projectId;\n}\n\nexport function getApiKey(firebaseApp: FirebaseApp): string {\n const apiKey = firebaseApp.options?.apiKey;\n if (!apiKey) {\n throw ERROR_FACTORY.create(ErrorCode.NO_API_KEY);\n }\n return apiKey;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\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';\nimport { PerformanceController } from '../controllers/perf';\nimport { getProjectId, getApiKey, getAppId } from '../utils/app_utils';\n\nconst REMOTE_CONFIG_SDK_VERSION = '0.0.1';\n\ninterface SecondaryConfig {\n loggingEnabled?: boolean;\n logSource?: number;\n logEndPointUrl?: string;\n transportKey?: string;\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 DEFAULT_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_log_transport_key?: string;\n fpr_log_transport_web_percent?: 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(\n performanceController: PerformanceController,\n iid: string\n): Promise<void> {\n const config = getStoredConfig();\n if (config) {\n processConfig(config);\n return Promise.resolve();\n }\n\n return getRemoteConfig(performanceController, iid)\n .then(processConfig)\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 performanceController: PerformanceController,\n iid: string\n): Promise<RemoteConfigResponse | undefined> {\n // Perf needs auth token only to retrieve remote config.\n return getAuthTokenPromise(performanceController.installations)\n .then(authToken => {\n const projectId = getProjectId(performanceController.app);\n const apiKey = getApiKey(performanceController.app);\n const configEndPoint = `https://firebaseremoteconfig.googleapis.com/v1/projects/${projectId}/namespaces/fireperf:fetch?key=${apiKey}`;\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: getAppId(performanceController.app),\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 valid.\n */\nfunction processConfig(\n config?: RemoteConfigResponse\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 (DEFAULT_CONFIGS.loggingEnabled !== undefined) {\n // Config retrieved successfully, but there is no fpr_enabled in template.\n // Use secondary configs value.\n settingsServiceInstance.loggingEnabled = DEFAULT_CONFIGS.loggingEnabled;\n }\n if (entries.fpr_log_source) {\n settingsServiceInstance.logSource = Number(entries.fpr_log_source);\n } else if (DEFAULT_CONFIGS.logSource) {\n settingsServiceInstance.logSource = DEFAULT_CONFIGS.logSource;\n }\n\n if (entries.fpr_log_endpoint_url) {\n settingsServiceInstance.logEndPointUrl = entries.fpr_log_endpoint_url;\n } else if (DEFAULT_CONFIGS.logEndPointUrl) {\n settingsServiceInstance.logEndPointUrl = DEFAULT_CONFIGS.logEndPointUrl;\n }\n\n // Key from Remote Config has to be non-empty string, otherwsie use local value.\n if (entries.fpr_log_transport_key) {\n settingsServiceInstance.transportKey = entries.fpr_log_transport_key;\n } else if (DEFAULT_CONFIGS.transportKey) {\n settingsServiceInstance.transportKey = DEFAULT_CONFIGS.transportKey;\n }\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 (DEFAULT_CONFIGS.networkRequestsSamplingRate !== undefined) {\n settingsServiceInstance.networkRequestsSamplingRate =\n DEFAULT_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 (DEFAULT_CONFIGS.tracesSamplingRate !== undefined) {\n settingsServiceInstance.tracesSamplingRate =\n DEFAULT_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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getIidPromise } from './iid_service';\nimport { getConfig } from './remote_config_service';\nimport { Api } from './api_service';\nimport { PerformanceController } from '../controllers/perf';\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(\n performanceController: PerformanceController\n): Promise<void> {\n initializationStatus = InitializationStatus.initializationPending;\n\n initializationPromise =\n initializationPromise || initializePerf(performanceController);\n\n return initializationPromise;\n}\n\nexport function isPerfInitialized(): boolean {\n return initializationStatus === InitializationStatus.initialized;\n}\n\nfunction initializePerf(\n performanceController: PerformanceController\n): Promise<void> {\n return getDocumentReadyComplete()\n .then(() => getIidPromise(performanceController.installations))\n .then(iid => getConfig(performanceController, 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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;\nconst MAX_EVENT_COUNT_PER_REQUEST = 1000;\nlet remainingTries = DEFAULT_REMAINING_TRIES;\n\ninterface LogResponseDetails {\n responseAction?: string;\n}\n\ninterface BatchEvent {\n message: string;\n eventTime: number;\n}\n\n/* eslint-disable camelcase */\n// CC/Fl accepted log format.\ninterface TransportBatchLogFormat {\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\n/**\n * Utilized by testing to clean up message queue and un-initialize transport service.\n */\nexport function resetTransportService(): void {\n isTransportSetup = false;\n queue = [];\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 dispatchQueueEvents();\n }, timeOffset);\n}\n\nfunction dispatchQueueEvents(): void {\n // Extract events up to the maximum cap of single logRequest from top of \"official queue\".\n // The staged events will be used for current logRequest attempt, remaining events will be kept\n // for next attempt.\n const staged = queue.splice(0, MAX_EVENT_COUNT_PER_REQUEST);\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: TransportBatchLogFormat = {\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 sendEventsToFl(data, staged).catch(() => {\n // If the request fails for some reason, add the events that were attempted\n // back to the primary queue to retry later.\n queue = [...staged, ...queue];\n remainingTries--;\n consoleLogger.info(`Tries left: ${remainingTries}.`);\n processQueue(DEFAULT_SEND_INTERVAL_MS);\n });\n}\n\nfunction sendEventsToFl(\n data: TransportBatchLogFormat,\n staged: BatchEvent[]\n): Promise<void> {\n return postToFlEndpoint(data)\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 // Find the next call wait time from the response.\n const transportWait = Number(res.nextRequestWaitMillis);\n let requestOffset = DEFAULT_SEND_INTERVAL_MS;\n if (!isNaN(transportWait)) {\n requestOffset = Math.max(transportWait, requestOffset);\n }\n\n // Delete request if response include RESPONSE_ACTION_UNKNOWN or DELETE_REQUEST action.\n // Otherwise, retry request using normal scheduling if response include RETRY_REQUEST_LATER.\n const logResponseDetails: LogResponseDetails[] = res.logResponseDetails;\n if (\n Array.isArray(logResponseDetails) &&\n logResponseDetails.length > 0 &&\n logResponseDetails[0].responseAction === 'RETRY_REQUEST_LATER'\n ) {\n queue = [...staged, ...queue];\n consoleLogger.info(`Retry transport request later.`);\n }\n\n remainingTries = DEFAULT_REMAINING_TRIES;\n // Schedule the next process.\n processQueue(requestOffset);\n });\n}\n\nfunction postToFlEndpoint(data: TransportBatchLogFormat): Promise<Response> {\n const flTransportFullUrl =\n SettingsService.getInstance().getFlTransportFullUrl();\n return fetch(flTransportFullUrl, {\n method: 'POST',\n body: JSON.stringify(data)\n });\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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';\nimport { FirebaseApp } from '@firebase/app';\nimport { getAppId } from '../utils/app_utils';\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\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 (isPerfInitialized()) {\n sendTraceLog(trace);\n } else {\n // Custom traces can be used before the initialization but logging\n // should wait until after.\n getInitializationPromise(trace.performanceController).then(\n () => sendTraceLog(trace),\n () => sendTraceLog(trace)\n );\n }\n}\n\nfunction sendTraceLog(trace: Trace): void {\n if (!getIid()) {\n return;\n }\n\n const settingsService = SettingsService.getInstance();\n if (\n !settingsService.loggingEnabled ||\n !settingsService.logTraceAfterSampling\n ) {\n return;\n }\n\n setTimeout(() => sendLog(trace, ResourceType.Trace), 0);\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\n // Do not log the js sdk's call to transport service domain to avoid unnecessary cycle.\n // Need to blacklist both old and new endpoints to avoid migration gap.\n const networkRequestUrl = networkRequest.url;\n\n // Blacklist old log endpoint and new transport endpoint.\n // Because Performance SDK doesn't instrument requests sent from SDK itself.\n const logEndpointUrl = settingsService.logEndPointUrl.split('?')[0];\n const flEndpointUrl = settingsService.flTransportEndpointUrl.split('?')[0];\n if (\n networkRequestUrl === logEndpointUrl ||\n networkRequestUrl === flEndpointUrl\n ) {\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 networkRequest.performanceController.app\n ),\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(trace.performanceController.app),\n trace_metric: traceMetric\n };\n return JSON.stringify(perfMetric);\n}\n\nfunction getApplicationInfo(firebaseApp: FirebaseApp): ApplicationInfo {\n return {\n google_app_id: getAppId(firebaseApp),\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\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';\nimport { consoleLogger } from '../utils/console_logger';\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/**\n * Converts the provided value to an integer value to be used in case of a metric.\n * @param providedValue Provided number value of the metric that needs to be converted to an integer.\n *\n * @returns Converted integer number to be set for the metric.\n */\nexport function convertMetricValueToInteger(providedValue: number): number {\n const valueAsInteger: number = Math.floor(providedValue);\n if (valueAsInteger < providedValue) {\n consoleLogger.info(\n `Metric value should be an Integer, setting the value as : ${valueAsInteger}.`\n );\n }\n return valueAsInteger;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\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 {\n isValidMetricName,\n convertMetricValueToInteger\n} from '../utils/metric_utils';\nimport { PerformanceTrace } from '../public_types';\nimport { PerformanceController } from '../controllers/perf';\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 performanceController The performance controller running.\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 performanceController: PerformanceController,\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 if (startTime <= 0) {\n throw ERROR_FACTORY.create(ErrorCode.NONPOSITIVE_TRACE_START_TIME, {\n traceName: this.name\n });\n }\n if (duration <= 0) {\n throw ERROR_FACTORY.create(ErrorCode.NONPOSITIVE_TRACE_DURATION, {\n traceName: this.name\n });\n }\n\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 metricName of Object.keys(options.metrics)) {\n if (!isNaN(Number(options.metrics[metricName]))) {\n this.counters[metricName] = Math.floor(\n Number(options.metrics[metricName])\n );\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. The value will be floored down to an\n * integer.\n * @param counter Name of the custom metric\n * @param numAsInteger Increment by value\n */\n incrementMetric(counter: string, numAsInteger = 1): void {\n if (this.counters[counter] === undefined) {\n this.putMetric(counter, numAsInteger);\n } else {\n this.putMetric(counter, this.counters[counter] + numAsInteger);\n }\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. The value will be floored down to an integer.\n * @param counter Name of the custom metric\n * @param numAsInteger Set custom metric to this value\n */\n putMetric(counter: string, numAsInteger: number): void {\n if (isValidMetricName(counter, this.name)) {\n this.counters[counter] = convertMetricValueToInteger(numAsInteger ?? 0);\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 performanceController: PerformanceController,\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(\n performanceController,\n OOB_TRACE_PAGE_LOAD_PREFIX + route,\n true\n );\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(\n performanceController: PerformanceController,\n measureName: string\n ): void {\n const trace = new Trace(\n performanceController,\n measureName,\n false,\n measureName\n );\n logTrace(trace);\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Api } from '../services/api_service';\nimport { logNetworkRequest } from '../services/perf_logger';\nimport { PerformanceController } from '../controllers/perf';\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 performanceController: PerformanceController;\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(\n performanceController: PerformanceController,\n entry: PerformanceEntry\n): 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 performanceController,\n url,\n responsePayloadBytes: performanceEntry.transferSize,\n startTimeUs,\n timeToResponseInitiatedUs,\n timeToResponseCompletedUs\n };\n\n logNetworkRequest(networkRequest);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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';\nimport { PerformanceController } from '../controllers/perf';\n\nconst FID_WAIT_TIME_MS = 5000;\n\nexport function setupOobResources(\n performanceController: PerformanceController\n): 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(performanceController), 0);\n setTimeout(() => setupNetworkRequests(performanceController), 0);\n setTimeout(() => setupUserTimingTraces(performanceController), 0);\n}\n\nfunction setupNetworkRequests(\n performanceController: PerformanceController\n): void {\n const api = Api.getInstance();\n const resources = api.getEntriesByType('resource');\n for (const resource of resources) {\n createNetworkRequestEntry(performanceController, resource);\n }\n api.setupObserver('resource', entry =>\n createNetworkRequestEntry(performanceController, entry)\n );\n}\n\nfunction setupOobTraces(performanceController: PerformanceController): 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(\n performanceController,\n navigationTimings,\n paintTimings\n );\n timeoutId = undefined;\n }, FID_WAIT_TIME_MS);\n api.onFirstInputDelay((fid: number) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n Trace.createOobTrace(\n performanceController,\n navigationTimings,\n paintTimings,\n fid\n );\n }\n });\n } else {\n Trace.createOobTrace(\n performanceController,\n navigationTimings,\n paintTimings\n );\n }\n}\n\nfunction setupUserTimingTraces(\n performanceController: PerformanceController\n): 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(performanceController, measure);\n }\n // Setup an observer to capture the measures from this point on.\n api.setupObserver('measure', entry =>\n createUserTimingTrace(performanceController, entry)\n );\n}\n\nfunction createUserTimingTrace(\n performanceController: PerformanceController,\n measure: PerformanceEntry\n): 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(performanceController, measureName);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { PerformanceSettings, FirebasePerformance } from '../public_types';\nimport { validateIndexedDBOpenable } from '@firebase/util';\nimport { setupTransportService } from '../services/transport_service';\nimport { consoleLogger } from '../utils/console_logger';\n\nexport class PerformanceController implements FirebasePerformance {\n private initialized: boolean = false;\n\n constructor(\n readonly app: FirebaseApp,\n readonly installations: _FirebaseInstallationsInternal\n ) {}\n\n /**\n * This method *must* be called internally as part of creating a\n * PerformanceController instance.\n *\n * Currently it's not possible to pass the settings object through the\n * constructor using Components, so this method exists to be called with the\n * desired settings, to ensure nothing is collected without the user's\n * consent.\n */\n _init(settings?: PerformanceSettings): void {\n if (this.initialized) {\n return;\n }\n\n if (settings?.dataCollectionEnabled !== undefined) {\n this.dataCollectionEnabled = settings.dataCollectionEnabled;\n }\n if (settings?.instrumentationEnabled !== undefined) {\n this.instrumentationEnabled = settings.instrumentationEnabled;\n }\n\n if (Api.getInstance().requiredApisAvailable()) {\n validateIndexedDBOpenable()\n .then(isAvailable => {\n if (isAvailable) {\n setupTransportService();\n getInitializationPromise(this).then(\n () => setupOobResources(this),\n () => setupOobResources(this)\n );\n this.initialized = true;\n }\n })\n .catch(error => {\n consoleLogger.info(`Environment doesn't support IndexedDB: ${error}`);\n });\n } else {\n consoleLogger.info(\n 'Firebase Performance cannot start if the browser does not support ' +\n '\"Fetch\" and \"Promise\", or cookies are disabled.'\n );\n }\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 * The Firebase Performance Monitoring Web SDK.\n * This SDK does not work in a Node.js environment.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebasePerformance,\n PerformanceSettings,\n PerformanceTrace\n} from './public_types';\nimport { ERROR_FACTORY, ErrorCode } from './utils/errors';\nimport { setupApi } from './services/api_service';\nimport { PerformanceController } from './controllers/perf';\nimport {\n _registerComponent,\n _getProvider,\n registerVersion,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n InstanceFactory,\n ComponentContainer,\n Component,\n ComponentType\n} from '@firebase/component';\nimport { name, version } from '../package.json';\nimport { Trace } from './resources/trace';\nimport '@firebase/installations';\nimport { deepEqual, getModularInstance } from '@firebase/util';\n\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\n * Returns a {@link FirebasePerformance} instance for the given app.\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n * @public\n */\nexport function getPerformance(\n app: FirebaseApp = getApp()\n): FirebasePerformance {\n app = getModularInstance(app);\n const provider = _getProvider(app, 'performance');\n const perfInstance = provider.getImmediate() as PerformanceController;\n return perfInstance;\n}\n\n/**\n * Returns a {@link FirebasePerformance} instance for the given app. Can only be called once.\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n * @param settings - Optional settings for the {@link FirebasePerformance} instance.\n * @public\n */\nexport function initializePerformance(\n app: FirebaseApp,\n settings?: PerformanceSettings\n): FirebasePerformance {\n app = getModularInstance(app);\n const provider = _getProvider(app, 'performance');\n\n // throw if an instance was already created.\n // It could happen if initializePerformance() is called more than once, or getPerformance() is called first.\n if (provider.isInitialized()) {\n const existingInstance = provider.getImmediate();\n const initialSettings = provider.getOptions() as PerformanceSettings;\n if (deepEqual(initialSettings, settings ?? {})) {\n return existingInstance;\n } else {\n throw ERROR_FACTORY.create(ErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const perfInstance = provider.initialize({\n options: settings\n }) as PerformanceController;\n return perfInstance;\n}\n\n/**\n * Returns a new `PerformanceTrace` instance.\n * @param performance - The {@link FirebasePerformance} instance to use.\n * @param name - The name of the trace.\n * @public\n */\nexport function trace(\n performance: FirebasePerformance,\n name: string\n): PerformanceTrace {\n performance = getModularInstance(performance);\n return new Trace(performance as PerformanceController, name);\n}\n\nconst factory: InstanceFactory<'performance'> = (\n container: ComponentContainer,\n { options: settings }: { options?: PerformanceSettings }\n) => {\n // Dependencies\n const app = container.getProvider('app').getImmediate();\n const installations = container\n .getProvider('installations-internal')\n .getImmediate();\n\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 const perfInstance = new PerformanceController(app, installations);\n perfInstance._init(settings);\n\n return perfInstance;\n};\n\nfunction registerPerformance(): void {\n _registerComponent(\n new Component('performance', factory, ComponentType.PUBLIC)\n );\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\nregisterPerformance();\n\nexport { FirebasePerformance, PerformanceSettings, PerformanceTrace };\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n trace,\n FirebasePerformance,\n // The PerformanceTrace type has not changed between modular and non-modular packages.\n PerformanceTrace\n} from '@firebase/performance';\nimport { FirebasePerformance as FirebasePerformanceCompat } from '@firebase/performance-types';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\n\nexport class PerformanceCompatImpl\n implements FirebasePerformanceCompat, _FirebaseService\n{\n constructor(\n public app: FirebaseApp,\n readonly _delegate: FirebasePerformance\n ) {}\n\n get instrumentationEnabled(): boolean {\n return this._delegate.instrumentationEnabled;\n }\n\n set instrumentationEnabled(val: boolean) {\n this._delegate.instrumentationEnabled = val;\n }\n\n get dataCollectionEnabled(): boolean {\n return this._delegate.dataCollectionEnabled;\n }\n\n set dataCollectionEnabled(val: boolean) {\n this._delegate.dataCollectionEnabled = val;\n }\n\n trace(traceName: string): PerformanceTrace {\n return trace(this._delegate, traceName);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const RC_COMPONENT_NAME = 'remote-config';\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 INDEXED_DB_UNAVAILABLE = 'indexed-db-unavailable'\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 [ErrorCode.INDEXED_DB_UNAVAILABLE]:\n 'Indexed DB is not supported by current browser'\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport {\n LogLevel as RemoteConfigLogLevel,\n RemoteConfig,\n Value\n} from './public_types';\nimport { RemoteConfigAbortSignal } from './client/remote_config_fetch_client';\nimport { RC_COMPONENT_NAME } from './constants';\nimport { ErrorCode, hasErrorCode } from './errors';\nimport { RemoteConfig as RemoteConfigImpl } from './remote_config';\nimport { Value as ValueImpl } from './value';\nimport { LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\n * @returns A {@link RemoteConfig} instance.\n *\n * @public\n */\nexport function getRemoteConfig(app: FirebaseApp = getApp()): RemoteConfig {\n app = getModularInstance(app);\n const rcProvider = _getProvider(app, RC_COMPONENT_NAME);\n return rcProvider.getImmediate();\n}\n\n/**\n * Makes the last fetched config available to the getters.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @returns A `Promise` which resolves to true if the current call activated the fetched configs.\n * If the fetched configs were already activated, the `Promise` will resolve to false.\n *\n * @public\n */\nexport async function activate(remoteConfig: RemoteConfig): Promise<boolean> {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([\n rc._storage.getLastSuccessfulFetchResponse(),\n rc._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 rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),\n rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag)\n ]);\n return true;\n}\n\n/**\n * Ensures the last activated config are available to the getters.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n *\n * @returns A `Promise` that resolves when the last activated config is available to the getters.\n * @public\n */\nexport function ensureInitialized(remoteConfig: RemoteConfig): Promise<void> {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n if (!rc._initializePromise) {\n rc._initializePromise = rc._storageCache.loadFromStorage().then(() => {\n rc._isInitializationComplete = true;\n });\n }\n return rc._initializePromise;\n}\n\n/**\n * Fetches and caches configuration from the Remote Config service.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @public\n */\nexport async function fetchConfig(remoteConfig: RemoteConfig): Promise<void> {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\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 }, rc.settings.fetchTimeoutMillis);\n\n // Catches *all* errors thrown by client so status can be set consistently.\n try {\n await rc._client.fetch({\n cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis,\n signal: abortSignal\n });\n\n await rc._storageCache.setLastFetchStatus('success');\n } catch (e) {\n const lastFetchStatus = hasErrorCode(e as Error, ErrorCode.FETCH_THROTTLE)\n ? 'throttle'\n : 'failure';\n await rc._storageCache.setLastFetchStatus(lastFetchStatus);\n throw e;\n }\n}\n\n/**\n * Gets all config.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @returns All config.\n *\n * @public\n */\nexport function getAll(remoteConfig: RemoteConfig): Record<string, Value> {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n return getAllKeys(\n rc._storageCache.getActiveConfig(),\n rc.defaultConfig\n ).reduce((allConfigs, key) => {\n allConfigs[key] = getValue(remoteConfig, key);\n return allConfigs;\n }, {} as Record<string, Value>);\n}\n\n/**\n * Gets the value for the given key as a boolean.\n *\n * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a boolean.\n * @public\n */\nexport function getBoolean(remoteConfig: RemoteConfig, key: string): boolean {\n return getValue(getModularInstance(remoteConfig), key).asBoolean();\n}\n\n/**\n * Gets the value for the given key as a number.\n *\n * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a number.\n *\n * @public\n */\nexport function getNumber(remoteConfig: RemoteConfig, key: string): number {\n return getValue(getModularInstance(remoteConfig), key).asNumber();\n}\n\n/**\n * Gets the value for the given key as a string.\n * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a string.\n *\n * @public\n */\nexport function getString(remoteConfig: RemoteConfig, key: string): string {\n return getValue(getModularInstance(remoteConfig), key).asString();\n}\n\n/**\n * Gets the {@link Value} for the given key.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key.\n *\n * @public\n */\nexport function getValue(remoteConfig: RemoteConfig, key: string): Value {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n if (!rc._isInitializationComplete) {\n rc._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 = rc._storageCache.getActiveConfig();\n if (activeConfig && activeConfig[key] !== undefined) {\n return new ValueImpl('remote', activeConfig[key]);\n } else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) {\n return new ValueImpl('default', String(rc.defaultConfig[key]));\n }\n rc._logger.debug(\n `Returning static value for key \"${key}\".` +\n ' Define a default or remote value if this is unintentional.'\n );\n return new ValueImpl('static');\n}\n\n/**\n * Defines the log level to use.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param logLevel - The log level to set.\n *\n * @public\n */\nexport function setLogLevel(\n remoteConfig: RemoteConfig,\n logLevel: RemoteConfigLogLevel\n): void {\n const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n switch (logLevel) {\n case 'debug':\n rc._logger.logLevel = FirebaseLogLevel.DEBUG;\n break;\n case 'silent':\n rc._logger.logLevel = FirebaseLogLevel.SILENT;\n break;\n default:\n rc._logger.logLevel = FirebaseLogLevel.ERROR;\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 [lastSuccessfulFetchTimestampMillis, 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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchResponse,\n RemoteConfigFetchClient,\n FirebaseRemoteConfigObject,\n FetchRequest\n} from './remote_config_fetch_client';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\nimport { getUserLanguage } from '../language';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\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: _FirebaseInstallationsInternal,\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 as Error)?.name === 'AbortError') {\n errorCode = ErrorCode.FETCH_TIMEOUT;\n }\n throw ERROR_FACTORY.create(errorCode, {\n originalErrorMessage: (originalError as Error)?.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 as Error)?.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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n RemoteConfigAbortSignal,\n RemoteConfigFetchClient,\n FetchResponse,\n FetchRequest\n} from './remote_config_fetch_client';\nimport { ThrottleMetadata, Storage } from '../storage/storage';\nimport { ErrorCode, ERROR_FACTORY } from '../errors';\nimport { FirebaseError, calculateBackoffMillis } 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\ntype RetriableError = FirebaseError & { customData: { httpStatus: string } };\n/**\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\n */\nfunction isRetriableError(e: Error): e is RetriableError {\n if (!(e instanceof FirebaseError) || !e.customData) {\n return false;\n }\n\n // Uses string index defined by ErrorData, which FirebaseError implements.\n const httpStatus = Number(e.customData['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 as Error)) {\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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n RemoteConfig as RemoteConfigType,\n FetchStatus,\n RemoteConfigSettings\n} from './public_types';\nimport { StorageCache } from './storage/storage_cache';\nimport { RemoteConfigFetchClient } from './client/remote_config_fetch_client';\nimport { Storage } from './storage/storage';\nimport { Logger } 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 /**\n * Tracks completion of initialization promise.\n * @internal\n */\n _isInitializationComplete = false;\n\n /**\n * De-duplicates initialization calls.\n * @internal\n */\n _initializePromise?: Promise<void>;\n\n settings: RemoteConfigSettings = {\n fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS,\n minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS\n };\n\n defaultConfig: { [key: string]: string | number | boolean } = {};\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 /**\n * @internal\n */\n readonly _client: RemoteConfigFetchClient,\n /**\n * @internal\n */\n readonly _storageCache: StorageCache,\n /**\n * @internal\n */\n readonly _storage: Storage,\n /**\n * @internal\n */\n readonly _logger: Logger\n ) {}\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 as Error)?.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 try {\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 } catch (error) {\n reject(\n ERROR_FACTORY.create(ErrorCode.STORAGE_OPEN, {\n originalErrorMessage: (error as Error)?.message\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 as Error)?.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 as Error)?.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 as Error)?.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 LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 =\n 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 =\n await lastSuccessfulFetchTimestampMillisPromise;\n if (lastSuccessfulFetchTimestampMillis) {\n this.lastSuccessfulFetchTimestampMillis =\n 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RemoteConfig } from './public_types';\nimport { activate, fetchConfig } from './api';\nimport {\n getModularInstance,\n isIndexedDBAvailable,\n validateIndexedDBOpenable\n} from '@firebase/util';\n\n// This API is put in a separate file, so we can stub fetchConfig and activate in tests.\n// It's not possible to stub standalone functions from the same module.\n/**\n *\n * Performs fetch and activate operations, as a convenience.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n *\n * @returns A `Promise` which resolves to true if the current call activated the fetched configs.\n * If the fetched configs were already activated, the `Promise` will resolve to false.\n *\n * @public\n */\nexport async function fetchAndActivate(\n remoteConfig: RemoteConfig\n): Promise<boolean> {\n remoteConfig = getModularInstance(remoteConfig);\n await fetchConfig(remoteConfig);\n return activate(remoteConfig);\n}\n\n/**\n * This method provides two different checks:\n *\n * 1. Check if IndexedDB exists in the browser environment.\n * 2. Check if the current browser context allows IndexedDB `open()` calls.\n *\n * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance\n * can be initialized in this environment, or false if it cannot.\n * @public\n */\nexport async function isSupported(): Promise<boolean> {\n if (!isIndexedDBAvailable()) {\n return false;\n }\n\n try {\n const isDBOpenable: boolean = await validateIndexedDBOpenable();\n return isDBOpenable;\n } catch (error) {\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { isIndexedDBAvailable } from '@firebase/util';\nimport {\n Component,\n ComponentType,\n ComponentContainer,\n InstanceFactoryOptions\n} from '@firebase/component';\nimport { Logger, LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { RemoteConfig } from './public_types';\nimport { name as packageName, version } from '../package.json';\nimport { ensureInitialized } from './api';\nimport { CachingClient } from './client/caching_client';\nimport { RestClient } from './client/rest_client';\nimport { RetryingClient } from './client/retrying_client';\nimport { RC_COMPONENT_NAME } from './constants';\nimport { ErrorCode, ERROR_FACTORY } from './errors';\nimport { RemoteConfig as RemoteConfigImpl } from './remote_config';\nimport { Storage } from './storage/storage';\nimport { StorageCache } from './storage/storage_cache';\n// This needs to be in the same file that calls `getProvider()` on the component\n// or it will get tree-shaken out.\nimport '@firebase/installations';\n\nexport function registerRemoteConfig(): void {\n _registerComponent(\n new Component(\n RC_COMPONENT_NAME,\n remoteConfigFactory,\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n\n registerVersion(packageName, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(packageName, version, '__BUILD_TARGET__');\n\n function remoteConfigFactory(\n container: ComponentContainer,\n { instanceIdentifier: namespace }: InstanceFactoryOptions\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\n .getProvider('installations-internal')\n .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 // Guards against the SDK being used when indexedDB is not available.\n if (!isIndexedDBAvailable()) {\n throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNAVAILABLE);\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 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 RemoteConfigImpl(\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 ensureInitialized(remoteConfigInstance);\n\n return remoteConfigInstance;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\nimport {\n Value as ValueCompat,\n FetchStatus as FetchSTatusCompat,\n Settings as SettingsCompat,\n LogLevel as RemoteConfigLogLevel,\n RemoteConfig as RemoteConfigCompat\n} from '@firebase/remote-config-types';\nimport {\n RemoteConfig,\n setLogLevel,\n activate,\n ensureInitialized,\n fetchAndActivate,\n fetchConfig,\n getAll,\n getBoolean,\n getNumber,\n getString,\n getValue,\n isSupported\n} from '@firebase/remote-config';\n\nexport { isSupported };\n\nexport class RemoteConfigCompatImpl\n implements RemoteConfigCompat, _FirebaseService\n{\n constructor(public app: FirebaseApp, readonly _delegate: RemoteConfig) {}\n\n get defaultConfig(): { [key: string]: string | number | boolean } {\n return this._delegate.defaultConfig;\n }\n\n set defaultConfig(value: { [key: string]: string | number | boolean }) {\n this._delegate.defaultConfig = value;\n }\n\n get fetchTimeMillis(): number {\n return this._delegate.fetchTimeMillis;\n }\n\n get lastFetchStatus(): FetchSTatusCompat {\n return this._delegate.lastFetchStatus;\n }\n\n get settings(): SettingsCompat {\n return this._delegate.settings;\n }\n\n set settings(value: SettingsCompat) {\n this._delegate.settings = value;\n }\n\n activate(): Promise<boolean> {\n return activate(this._delegate);\n }\n\n ensureInitialized(): Promise<void> {\n return ensureInitialized(this._delegate);\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 fetch(): Promise<void> {\n return fetchConfig(this._delegate);\n }\n\n fetchAndActivate(): Promise<boolean> {\n return fetchAndActivate(this._delegate);\n }\n\n getAll(): { [key: string]: ValueCompat } {\n return getAll(this._delegate);\n }\n\n getBoolean(key: string): boolean {\n return getBoolean(this._delegate, key);\n }\n\n getNumber(key: string): number {\n return getNumber(this._delegate, key);\n }\n\n getString(key: string): string {\n return getString(this._delegate, key);\n }\n\n getValue(key: string): ValueCompat {\n return getValue(this._delegate, key);\n }\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 setLogLevel(this._delegate, logLevel);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 from './app';\nimport { name, version } from '../package.json';\n\nimport './analytics';\nimport './app-check';\nimport './auth';\nimport './database';\nimport './firestore';\nimport './functions';\nimport './messaging';\nimport './storage';\nimport './performance';\nimport './remote-config';\n\nfirebase.registerVersion(name, version, 'compat-cdn');\n\nexport default firebase;\n"],"names":["CONSTANTS","NODE_CLIENT","NODE_ADMIN","SDK_VERSION","assert","assertion","message","assertionError","Error","stringToByteArray","str","out","p","i","length","c","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte3","outByte4","push","join","encodeString","btoa","decodeString","bytes","pos","c2","c3","c1","String","fromCharCode","u","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","name","base64Encode","utf8Bytes","base64urlEncodeWithoutPadding","replace","base64Decode","e","console","error","deepExtend","target","source","Object","Date","dateValue","getTime","undefined","prop","hasOwnProperty","getGlobal","self","window","global","getDefaultsFromGlobal","__FIREBASE_DEFAULTS__","getDefaultsFromEnvVariable","process","env","defaultsJsonString","JSON","parse","getDefaultsFromCookie","document","match","cookie","decoded","getDefaults","info","getDefaultAppConfig","_a","config","LogLevel","Deferred","reject","resolve","promise","Promise","wrapCallback","callback","value","catch","createMockUserToken","token","projectId","uid","project","iat","sub","user_id","payload","assign","iss","aud","exp","auth_time","firebase","sign_in_provider","identities","stringify","alg","type","getUA","navigator","isMobileCordova","test","isNode","forceEnvironment","prototype","toString","call","isBrowserExtension","runtime","chrome","browser","id","isReactNative","isIE","ua","indexOf","isNodeSdk","isSafari","userAgent","includes","isIndexedDBAvailable","indexedDB","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","request","open","onsuccess","result","close","deleteDatabase","onupgradeneeded","onerror","areCookiesEnabled","cookieEnabled","FirebaseError","code","customData","super","setPrototypeOf","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","PATTERN","_","key","fullMessage","jsonEval","decode","header","claims","signature","parts","split","contains","obj","safeGet","isEmpty","map","fn","contextObj","res","deepEqual","a","b","aKeys","keys","bKeys","k","aProp","bProp","isObject","thing","querystring","querystringParams","params","entries","forEach","arrayVal","encodeURIComponent","querystringDecode","tokens","decodeURIComponent","extractQuerystring","url","queryStart","fragmentStart","substring","Sha1","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","offset","W","t","d","f","update","lengthMinusBlock","n","inbuf","digest","totalBits","j","createSubscribe","executor","onNoObservers","proxy","ObserverProxy","subscribe","bind","observers","unsubscribes","observerCount","task","finalized","then","next","forEachObserver","observer","complete","nextOrObserver","methods","method","implementsAnyMethods","noop","unsub","unsubscribeOne","finalError","sendOne","err","validateArgCount","fnName","minCount","maxCount","argCount","argError","errorPrefix","argName","validateCallback","argumentName","optional","validateContextObject","context","uuidv4","r","Math","random","v","stringLength","DEFAULT_INTERVAL_MILLIS","DEFAULT_BACKOFF_FACTOR","MAX_VALUE_MILLIS","RANDOM_FACTOR","calculateBackoffMillis","backoffCount","intervalMillis","backoffFactor","currBaseValue","pow","randomWait","round","min","getModularInstance","_delegate","Component","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","Provider","container","component","instances","Map","instancesDeferred","instancesOptions","onInitCallbacks","get","identifier","normalizedIdentifier","normalizeInstanceIdentifier","has","deferred","set","isInitialized","shouldAutoInitialize","instance","getOrInitializeService","instanceIdentifier","getImmediate","options","getComponent","setComponent","instanceDeferred","clearInstance","delete","services","from","values","all","filter","INTERNAL","_delete","isComponentSet","getOptions","initialize","opts","onInit","existingCallbacks","Set","add","existingInstance","invokeOnInitCallbacks","callbacks","ComponentContainer","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","logLevel","now","toISOString","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","log","instanceOfAny","object","constructors","some","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","receiver","IDBTransaction","objectStoreNames","objectStore","wrap","wrapFunction","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","apply","unwrap","storeNames","tx","sort","transformCachableValue","done","unlisten","removeEventListener","DOMException","addEventListener","IDBObjectStore","IDBIndex","Proxy","IDBRequest","success","promisifyRequest","newValue","openDB","version","blocked","upgrade","blocking","terminated","openPromise","event","oldVersion","newVersion","db","deleteDB","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","async","storeName","store","index","shift","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","library","logString","logger","variant","PLATFORM_LOG_STRING","@firebase/app","@firebase/app-compat","@firebase/analytics","@firebase/analytics-compat","@firebase/app-check","@firebase/app-check-compat","@firebase/auth","@firebase/auth-compat","@firebase/database","@firebase/database-compat","@firebase/functions","@firebase/functions-compat","@firebase/installations","@firebase/installations-compat","@firebase/messaging","@firebase/messaging-compat","@firebase/performance","@firebase/performance-compat","@firebase/remote-config","@firebase/remote-config-compat","@firebase/storage","@firebase/storage-compat","@firebase/firestore","@firebase/firestore-compat","fire-js","_apps","_components","_addComponent","app","_addOrOverwriteComponent","_registerComponent","componentName","_getProvider","heartbeatController","triggerHeartbeat","ERROR_FACTORY","no-app","bad-app-name","duplicate-app","app-deleted","no-options","invalid-app-argument","invalid-log-argument","idb-open","idb-get","idb-set","idb-delete","FirebaseAppImpl","_isDeleted","_options","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","initializeApp","rawConfig","existingApp","newApp","getApp","deleteApp","registerVersion","libraryKeyOrName","libraryMismatch","versionMismatch","warning","onLog","logCallback","customLogLevel","level","arg","ignored","toLowerCase","setUserLogHandler","inst","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","platformLogger","agent","date","getUTCDateString","heartbeats","_b","lastSentHeartbeatDate","singleDateHeartbeat","hbTimestamp","valueOf","overwrite","getHeartbeatsHeader","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","slice","heartbeatEntry","find","hb","dates","countBytes","pop","extractHeartbeatsForHeader","headerString","today","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","idbHeartbeatObject","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","clear","removeApp","_getService","_DEFAULT_ENTRY_NAME","_removeServiceInstance","toJSON","createFirebaseNamespaceCore","firebaseAppImpl","apps","namespace","__esModule","modularAPIs.initializeApp","appCompat","modularAPIs.registerVersion","modularAPIs.setLogLevel","modularAPIs.onLog","modularAPIs.SDK_VERSION","registerComponent","componentNameWithoutCompat","serviceNamespace","modularAPIs._registerComponent","appArg","serviceFxn","useAsService","useService","modularAPIs","modularAPIs._DEFAULT_ENTRY_NAME","defineProperty","createFirebaseNamespace","extendNamespace","sdkVersion","firebaseNamespace","registerCoreComponents","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","missing-app-config-values","not-registered","installation-not-found","request-failed","app-offline","delete-pending-registration","isServerError","getInstallationsEndpoint","extractAuthTokenInfoFromResponse","response","requestStatus","expiresIn","responseExpiresIn","Number","creationTime","getErrorFromResponse","requestName","errorData","json","serverCode","serverMessage","serverStatus","status","getHeaders","apiKey","Headers","Content-Type","Accept","x-goog-api-key","getHeadersWithAuth","appConfig","refreshToken","headers","append","retryIfServerError","sleep","ms","setTimeout","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","Uint8Array","crypto","msCrypto","getRandomValues","fid","b64String","array","b64","bufferToBase64UrlSafe","substr","encode","getKey","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","channel","broadcastChannel","BroadcastChannel","onmessage","getBroadcastChannel","postMessage","size","broadcastFidChange","OBJECT_STORE_NAME","oldValue","remove","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","clearTimedOutRequest","registrationStatus","entryWithPromise","entry","updateInstallationRequest","waitUntilFidRegistration","onLine","registrationPromiseWithError","inProgressEntry","registrationTime","registeredInstallationEntry","heartbeatServiceProvider","endpoint","heartbeatService","heartbeatsHeader","body","authVersion","fetch","ok","responseValue","authToken","createInstallationRequest","registerInstallation","triggerRegistrationIfNecessary","generateAuthTokenRequest","getGenerateAuthTokenEndpoint","installation","refreshAuthToken","forceRefresh","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenExpired","updateAuthTokenRequest","waitUntilAuthTokenRequest","inProgressAuthToken","requestTime","updatedInstallationEntry","fetchAuthTokenFromServer","getToken","installationsImpl","getMissingValueError","valueName","INSTALLATIONS_NAME","publicFactory","keyName","extractAppConfig","internalFactory","getId","ANALYTICS_TYPE","GA_FID_KEY","ORIGIN_KEY","DYNAMIC_CONFIG_URL","GTAG_URL","already-exists","already-initialized","already-initialized-settings","interop-component-reg-failed","invalid-analytics-context","indexeddb-unavailable","fetch-throttle","config-fetch-failed","no-api-key","no-app-id","no-client-id","invalid-gtag-resource","createGtagTrustedTypesScriptURL","startsWith","gtagURL","promiseAllSettled","promises","insertScriptTag","dataLayerName","measurementId","trustedTypesPolicy","policyName","policyOptions","trustedTypes","createPolicy","createTrustedTypesPolicy","createScriptURL","script","createElement","gtagScriptURL","src","head","appendChild","wrapGtag","gtagCore","initializationPromisesMap","dynamicConfigPromisesList","measurementIdToAppId","command","gtagParams","fieldName","customParams","initializationPromisesToWaitFor","gaSendToList","dynamicConfigResults","sendToId","foundConfig","initializationPromise","gtagOnEvent","correspondingAppId","gtagOnConfig","LONG_RETRY_FACTOR","defaultRetryData","throttleMetadata","getThrottleMetadata","setThrottleMetadata","metadata","deleteThrottleMetadata","fetchDynamicConfig","appFields","appUrl","errorMessage","jsonResponse","_ignored","httpStatus","responseMessage","fetchDynamicConfigWithRetry","retryData","timeoutMillis","throttleEndTimeMillis","signal","AnalyticsAbortSignal","abort","attemptFetchDynamicConfigWithRetry","setAbortableTimeout","isRetriableError","backoffMillis","max","timeout","clearTimeout","listeners","listener","_initializeAnalytics","dynamicConfigPromise","fidPromise","errorInfo","validateIndexedDB","envIsValid","dynamicConfig","scriptTags","getElementsByTagName","tag","findGtagScriptOnPage","configProperties","AnalyticsService","gtagName","gtagCoreFunction","wrappedGtagFunction","globalInitDone","settings","factory","mismatchedEnvMessages","details","warnOnBrowserContextMismatch","wrappedGtag","dataLayer","getOrCreateDataLayer","gtagFunctionName","arguments","wrapOrCreateGtag","isSupported","setCurrentScreen","analyticsInstance","screenName","gtagFunction","screen_name","internalSetCurrentScreen","setUserId","internalSetUserId","setUserProperties","properties","flatProperties","user_properties","internalSetUserProperties","setAnalyticsCollectionEnabled","enabled","internalSetAnalyticsCollectionEnabled","logEvent","eventName","eventParams","send_to","internalLogEvent","analyticsOptions","analytics","reason","EventName","namespaceExports","logEventExp","setCurrentScreenExp","setUserIdExp","setUserPropertiesExp","setAnalyticsCollectionEnabledExp","analyticsServiceExp","Analytics","settingsExp","isSupportedExp","APP_CHECK_STATES","DEFAULT_STATE","activated","tokenObservers","DEBUG_STATE","initialized","getStateReference","BASE_ENDPOINT","EXCHANGE_DEBUG_TOKEN_METHOD","TOKEN_REFRESH_TIME","OFFSET_DURATION","RETRIAL_MIN_WAIT","RETRIAL_MAX_WAIT","Refresher","operation","retryPolicy","getWaitDuration","lowerBound","upperBound","pending","nextErrorWaitInterval","start","stop","isRunning","hasSucceeded","_e","getNextRun","currentErrorWaitInterval","use-before-activation","fetch-network-error","fetch-parse-error","fetch-status-error","storage-open","storage-get","storage-set","recaptcha-error","throttled","getRecaptcha","isEnterprise","grecaptcha","enterprise","ensureActivated","getDurationString","durationInMillis","totalSeconds","days","floor","hours","minutes","seconds","pad","exchangeToken","originalError","responseBody","ttl","isNaN","timeToLiveAsNumber","expireTimeMillis","issuedAtTimeMillis","getExchangeDebugTokenRequest","debugToken","debug_token","DEBUG_TOKEN_KEY","getDBPromise","keyPath","write","compositeKey","_event","readTokenFromStorage","writeTokenToStorage","readOrCreateDebugTokenFromStorage","existingDebugToken","newToken","isDebugMode","getDebugToken","state","defaultTokenErrorData","appCheck","isValid","cachedToken","cachedTokenPromise","shouldCallListeners","exchangeTokenPromise","finally","tokenFromDebugExchange","interopTokenResult","internalError","makeDummyTokenResult","notifyTokenListeners","addTokenListener","onError","tokenObserver","validToken","initTokenRefresher","removeTokenListener","newObservers","tokenRefresher","refresher","nextRefreshTimeMillis","latestAllowableRefresh","createTokenRefresher","isTokenAutoRefreshEnabled","tokenErrorData","AppCheckService","getLimitedUseToken","RECAPTCHA_URL","RECAPTCHA_ENTERPRISE_URL","initializeV3","siteKey","reCAPTCHAState","divId","makeDiv","queueWidgetRender","onload","loadReCAPTCHAV3Script","initializeEnterprise","loadReCAPTCHAEnterpriseScript","ready","widgetId","render","sitekey","succeeded","error-callback","renderInvisibleWidget","invisibleDiv","style","display","recaptcha","_reject","execute","action","ReCaptchaV3Provider","_siteKey","_throttleData","throwIfThrottled","attestedClaimsToken","getReCAPTCHAToken","_app","reCAPTCHAToken","recaptcha_v3_token","getExchangeRecaptchaV3TokenRequest","_heartbeatServiceProvider","setBackoff","_c","time","allowRequestsAfter","initializeRecaptchaV3","isEqual","otherProvider","ReCaptchaEnterpriseProvider","recaptcha_enterprise_token","getExchangeRecaptchaEnterpriseTokenRequest","initializeRecaptchaEnterprise","CustomProvider","_customProviderOptions","customToken","issuedAtTimeSeconds","issuedAtTime","throttleData","initializeAppCheck","globals","debugState","FIREBASE_APPCHECK_DEBUG_TOKEN","deferredToken","initializeDebugMode","initialOptions","setInitialState","_activate","APP_CHECK_NAME_INTERNAL","_identifier","_appcheckService","activate","siteKeyOrProvider","setTokenAutoRefreshEnabled","appCheckInstance","setTokenAutoRefreshEnabledExp","getTokenInternal","getTokenExp","onTokenChanged","onNextOrObserver","onCompletion","nextFn","errorFn","onTokenChangedExp","__rest","s","getOwnPropertySymbols","propertyIsEnumerable","ProviderId","FACEBOOK","GITHUB","GOOGLE","PASSWORD","PHONE","TWITTER","ActionCodeOperation","EMAIL_SIGNIN","PASSWORD_RESET","RECOVER_EMAIL","REVERT_SECOND_FACTOR_ADDITION","VERIFY_AND_CHANGE_EMAIL","VERIFY_EMAIL","_prodErrorMap","dependent-sdk-initialized-before-auth","debugErrorMap","admin-restricted-operation","argument-error","app-not-authorized","app-not-installed","captcha-check-failed","code-expired","cordova-not-ready","cors-unsupported","credential-already-in-use","custom-token-mismatch","requires-recent-login","dynamic-link-not-activated","email-change-needs-verification","email-already-in-use","emulator-config-failed","expired-action-code","cancelled-popup-request","internal-error","invalid-app-credential","invalid-app-id","invalid-user-token","invalid-auth-event","invalid-verification-code","invalid-continue-uri","invalid-cordova-configuration","invalid-custom-token","invalid-dynamic-link-domain","invalid-email","invalid-emulator-scheme","invalid-api-key","invalid-cert-hash","invalid-credential","invalid-message-payload","invalid-multi-factor-session","invalid-oauth-provider","invalid-oauth-client-id","unauthorized-domain","invalid-action-code","wrong-password","invalid-persistence-type","invalid-phone-number","invalid-provider-id","invalid-recipient-email","invalid-sender","invalid-verification-id","invalid-tenant-id","login-blocked","missing-android-pkg-name","auth-domain-config-required","missing-app-credential","missing-verification-code","missing-continue-uri","missing-iframe-start","missing-ios-bundle-id","missing-or-invalid-nonce","missing-password","missing-multi-factor-info","missing-multi-factor-session","missing-phone-number","missing-verification-id","multi-factor-info-not-found","multi-factor-auth-required","account-exists-with-different-credential","network-request-failed","no-auth-event","no-such-provider","null-user","operation-not-allowed","operation-not-supported-in-this-environment","popup-blocked","popup-closed-by-user","provider-already-linked","quota-exceeded","redirect-cancelled-by-user","redirect-operation-pending","rejected-credential","second-factor-already-in-use","maximum-second-factor-count-exceeded","tenant-id-mismatch","user-token-expired","too-many-requests","unauthorized-continue-uri","unsupported-first-factor","unsupported-persistence-type","unsupported-tenant-operation","unverified-email","user-cancelled","user-not-found","user-disabled","user-mismatch","user-signed-out","weak-password","web-storage-unsupported","missing-recaptcha-token","invalid-recaptcha-token","invalid-recaptcha-action","recaptcha-not-enabled","missing-client-type","missing-recaptcha-version","invalid-req-type","invalid-recaptcha-version","unsupported-password-policy-schema-version","password-does-not-meet-requirements","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","msg","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","_assertInstanceOf","fullParams","_errorFactory","_assert","debugFail","failure","debugAssert","_getCurrentUrl","location","href","_isHttpOrHttps","_getCurrentScheme","protocol","Delay","shortDelay","longDelay","isMobile","_emulatorUrl","path","emulator","FetchProvider","fetchImpl","headersImpl","responseImpl","globalThis","Response","SERVER_ERROR_MAP","CREDENTIAL_MISMATCH","MISSING_CUSTOM_TOKEN","INVALID_IDENTIFIER","MISSING_CONTINUE_URI","INVALID_PASSWORD","MISSING_PASSWORD","INVALID_LOGIN_CREDENTIALS","EMAIL_EXISTS","PASSWORD_LOGIN_DISABLED","INVALID_IDP_RESPONSE","INVALID_PENDING_TOKEN","FEDERATED_USER_ID_ALREADY_LINKED","MISSING_REQ_TYPE","EMAIL_NOT_FOUND","RESET_PASSWORD_EXCEED_LIMIT","EXPIRED_OOB_CODE","INVALID_OOB_CODE","MISSING_OOB_CODE","CREDENTIAL_TOO_OLD_LOGIN_AGAIN","INVALID_ID_TOKEN","TOKEN_EXPIRED","USER_NOT_FOUND","TOO_MANY_ATTEMPTS_TRY_LATER","PASSWORD_DOES_NOT_MEET_REQUIREMENTS","INVALID_CODE","INVALID_SESSION_INFO","INVALID_TEMPORARY_PROOF","MISSING_SESSION_INFO","SESSION_EXPIRED","MISSING_ANDROID_PACKAGE_NAME","UNAUTHORIZED_DOMAIN","INVALID_OAUTH_CLIENT_ID","ADMIN_ONLY_OPERATION","INVALID_MFA_PENDING_CREDENTIAL","MFA_ENROLLMENT_NOT_FOUND","MISSING_MFA_ENROLLMENT_ID","MISSING_MFA_PENDING_CREDENTIAL","SECOND_FACTOR_EXISTS","SECOND_FACTOR_LIMIT_EXCEEDED","BLOCKING_FUNCTION_ERROR_RESPONSE","RECAPTCHA_NOT_ENABLED","MISSING_RECAPTCHA_TOKEN","INVALID_RECAPTCHA_TOKEN","INVALID_RECAPTCHA_ACTION","MISSING_CLIENT_TYPE","MISSING_RECAPTCHA_VERSION","INVALID_RECAPTCHA_VERSION","INVALID_REQ_TYPE","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","tenantId","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","query","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","race","clearNetworkTimeout","_makeTaggedError","serverErrorCode","serverErrorMessage","authError","_performSignInRequest","serverResponse","_serverResponse","host","base","apiScheme","timer","errorParams","email","phoneNumber","_tokenResponse","isV2","getResponse","RecaptchaConfig","recaptchaEnforcementState","recaptchaKey","getProviderEnforcementState","providerStr","enforcementStateStr","_parseEnforcementState","enforcementState","isProviderEnabled","utcTimestampToDateString","utcTimestamp","toUTCString","secondsStringToMilliseconds","_parseToken","algorithm","_logoutIfInvalidated","user","bypassAuthState","isUserInvalidated","currentUser","signOut","ProactiveRefresh","timerId","errorBackoff","_start","schedule","_stop","getInterval","wasError","interval","stsTokenManager","expirationTime","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","_copy","_reloadWithoutSaving","idToken","getAccountInfo","users","coreAccount","_notifyReloadListener","original","newData","newProviderData","providerUserInfo","providerId","rawId","displayName","photoURL","photoUrl","providerData","o","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","localId","emailVerified","StsTokenManager","accessToken","isExpired","updateFromServerResponse","parsedToken","updateTokensAndExpiration","refresh","clearRefreshToken","oldToken","grant_type","refresh_token","tokenApiHost","access_token","expires_in","expiresInSec","fromJSON","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","signInProvider","authTime","signInSecondFactor","reload","userInfo","newUser","_onReload","_startProactiveRefresh","_stopProactiveRefresh","_updateTokensIfNecessary","tokensRefreshed","deleteAccount","_redirectEventId","_fromJSON","_d","_f","_g","_h","plainObjectTokenManager","_fromIdTokenResponse","idTokenResponse","instanceCache","_getInstance","cls","Function","InMemoryPersistence","storage","_isAvailable","_set","_get","_remove","_addListener","_key","_listener","_removeListener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","getCurrentUser","blob","removeCurrentUser","savePersistenceForRedirect","setPersistence","newPersistence","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","matches","_isIOS","_isMobileBrowser","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","AuthMiddlewareQueue","queue","pushCallback","onAbort","wrappedCallback","runMiddleware","nextUser","onAbortStack","beforeStateCallback","reverse","originalMessage","PasswordPolicyImpl","responseOptions","customStrengthOptions","minPasswordLength","maxPasswordLength","containsLowercaseCharacter","containsLowercaseLetter","containsUppercaseCharacter","containsUppercaseLetter","containsNumericCharacter","containsNonAlphanumericCharacter","allowedNonAlphanumericCharacters","forceUpgradeOnSignin","schemaVersion","validatePassword","password","passwordPolicy","validatePasswordLengthOptions","validatePasswordCharacterOptions","meetsMinPasswordLength","meetsMaxPasswordLength","passwordChar","updatePasswordCharacterOptionsStatuses","AuthImpl","appCheckServiceProvider","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","_agentRecaptchaConfig","_tenantRecaptchaConfigs","_projectPasswordPolicy","_tenantPasswordPolicies","lastNotifiedUid","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","redirectUserEventId","storedUserEventId","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","tryRedirectSignIn","directlySetCurrentUser","reloadAndSetCurrentUserOrClear","_overrideRedirectResult","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","language","_getUserLanguage","updateCurrentUser","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","_getRecaptchaConfig","_getPasswordPolicyInternal","_updatePasswordPolicy","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","authStateReady","unsubscribe","revokeAccessToken","tokenType","redirectManager","resolver","_redirectPersistence","_redirectUserForId","currentUid","subscription","cb","isUnsubscribed","addObserver","_logFramework","framework","_getFrameworks","X-Client-Version","appCheckToken","_getAppCheckToken","appCheckTokenResult","_logWarn","_castAuth","externalJSProvider","loadJS","recaptchaV2Script","recaptchaEnterpriseScript","gapiScript","_loadJS","_generateCallbackName","prefix","RecaptchaEnterpriseVerifier","authExtern","verify","retrieveSiteKey","getRecaptchaConfig","clientType","retrieveRecaptchaToken","jsHelpers\r\n ._loadJS","injectRecaptchaFields","captchaResp","verifier","captchaResponse","newRequest","recaptchaVersion","handleRecaptchaFlow","authInstance","actionName","actionMethod","requestWithRecaptcha","connectAuthEmulator","authInternal","disableWarnings","extractProtocol","port","authority","exec","hostAndPort","bracketedIPv6","parsePort","extractHostAndPort","freeze","attachBanner","el","sty","innerText","position","width","backgroundColor","border","color","bottom","left","margin","zIndex","textAlign","classList","readyState","emitEmulatorWarning","protocolEnd","portStr","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","resetPassword","linkEmailPassword","signInWithPassword","sendOobCode","sendPasswordResetEmail","sendSignInLinkToEmail","EmailAuthCredential","_email","_password","_tenantId","_fromEmailAndPassword","_fromEmailAndCode","oobCode","returnSecureToken","signInWithEmailLink","signInWithEmailLinkForLinking","signInWithIdp","OAuthCredential","pendingToken","_fromParams","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","postBody","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","PhoneAuthCredential","_fromVerification","verificationId","verificationCode","_fromTokenResponse","temporaryProof","signInWithPhoneNumber","_makeVerificationRequest","linkWithPhoneNumber","verifyPhoneNumberForExisting","sessionInfo","ActionCodeURL","actionLink","searchParams","parseMode","continueUrl","parseLink","link","doubleDeepLink","iOSDeepLink","EmailAuthProvider","PROVIDER_ID","credential","credentialWithLink","emailLink","actionCodeUrl","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","OAuthProvider","credentialFromJSON","_credential","rawNonce","credentialFromResult","userCredential","oauthCredentialFromTaggedObject","credentialFromError","tokenResponse","oauthIdToken","oauthAccessToken","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromTaggedObject","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","SAMLAuthCredential","_create","SAMLAuthProvider","samlCredentialFromTaggedObject","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","signUp","UserCredentialImpl","operationType","providerIdForResponse","_forOperation","MultiFactorError","_fromErrorAndOperation","_processCredentialSavingMfaContextIfNecessary","idTokenProvider","providerDataAsNames","pid","unlink","_assertLinkedStatus","deleteProvider","providersLeft","pd","_link","expected","providerIds","_reauthenticate","parsed","_signInWithCredential","signInWithCredential","linkWithCredential","reauthenticateWithCredential","signInWithCustomToken","MultiFactorInfoImpl","factorId","mfaEnrollmentId","enrollmentTime","enrolledAt","_fromServerResponse","enrollment","PhoneMultiFactorInfoImpl","TotpMultiFactorInfoImpl","phoneInfo","_setActionCodeSettingsOnRequest","actionCodeSettings","dynamicLinkDomain","canHandleCodeInApp","handleCodeInApp","iOS","bundleId","iOSBundleId","android","packageName","androidInstallApp","installApp","androidMinimumVersionCode","minimumVersion","androidPackageName","recachePasswordPolicy","applyActionCode","checkActionCode","authModular","account.resetPassword","requestType","newEmail","mfaInfo","multiFactorInfo","previousEmail","fetchSignInMethodsForEmail","continueUri","signinMethods","sendEmailVerification","verifyBeforeUpdateEmail","updateProfile","apiUpdateProfile","passwordProvider","updateEmailOrPassword","apiUpdateEmailPassword","GenericAdditionalUserInfo","isNewUser","profile","FederatedAdditionalUserInfoWithUsername","username","FacebookAdditionalUserInfo","GithubAdditionalUserInfo","login","GoogleAdditionalUserInfo","TwitterAdditionalUserInfo","getAdditionalUserInfo","rawUserInfo","kind","filteredProviderId","MultiFactorSessionImpl","_fromIdtoken","_fromMfaPendingCredential","mfaPendingCredential","multiFactorSession","pendingCredential","MultiFactorResolverImpl","session","hints","signInResolver","_fromError","mfaResponse","_process","resolveSignIn","assertionExtern","MultiFactorUserImpl","enrolledFactors","_fromUser","getSession","enroll","finalizeMfaResponse","unenroll","infoOrUid","multiFactorUserCache","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","setItem","removeItem","getItem","BrowserLocalPersistence","localStorage","poll","onStorageEvent","localCache","pollTimer","safariLocalStorageNotSynced","top","_isIframe","fallbackToPolling","forAllChangedKeys","detachListener","stopPolling","storedValue","triggerListeners","notifyListeners","documentMode","_oldValue","startPolling","setInterval","StorageEvent","clearInterval","attachListener","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","handleEvent","receivers","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","handler","origin","fulfilled","_subscribe","eventHandler","_unsubscribe","_generateEventId","digits","Sender","removeMessageHandler","messageChannel","port1","onMessage","_send","MessageChannel","completionTimer","ackTimer","port2","_window","_isWorker","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","isReadWrite","_openDatabase","_putObject","fbase_key","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","_openDb","_withRetries","op","numAttempts","initializeReceiver","initializeSender","_origin","_poll","keyProcessed","_data","results","serviceWorker","active","_getActiveServiceWorker","notifyServiceWorker","controller","_withPendingWrite","getObject","getAllRequest","getAll","keysInResult","localKey","indexedDBLocalPersistence","MockReCaptcha","counter","_widgets","parameters","MockWidget","optWidgetId","containerOrId","deleted","responseToken","clickHandler","getElementById","isVisible","checkIfDeleted","len","chars","allowedChars","generateRandomAlphaNumericString","expired-callback","expiredCallback","_JSLOAD_CALLBACK","jsHelpers._generateCallbackName","NETWORK_TIMEOUT_DELAY","ReCaptchaLoaderImpl","hostLanguage","librarySeparatelyLoaded","load","hl","shouldResolveImmediately","jsHelpers._loadJS","clearedOneInstance","MockReCaptchaLoaderImpl","RECAPTCHA_VERIFIER_TYPE","DEFAULT_PARAMS","theme","RecaptchaVerifier","destroyed","tokenChangeListeners","renderPromise","isInvisible","makeTokenCallback","_recaptchaLoader","validateStartingState","assertNotDestroyed","getAssertedRecaptcha","tokenChange","makeRenderPromise","_reset","childNodes","node","removeChild","hasChildNodes","existing","globalFunc","init","guaranteedEmpty","domReady","recaptchaSiteKey","ConfirmationResultImpl","onConfirmation","confirm","authCredential","_verifyPhoneNumber","recaptchaToken","phoneInfoOptions","phoneEnrollmentInfo","phoneSessionInfo","multiFactorHint","multiFactorUid","phoneSignInInfo","phoneResponseInfo","PhoneAuthProvider","verifyPhoneNumber","phoneOptions","applicationVerifier","_withDefaultResolver","resolverOverride","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_reauth","_linkUser","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","onAuthEvent","urlResponse","getIdpTask","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","cancel","executeNotNull","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_getAndClearPendingRedirectStatus","_setPendingRedirectStatus","signInWithRedirect","resolverInternal","_openRedirect","_signInWithRedirect","reauthenticateWithRedirect","prepareUserForRedirect","_reauthenticateWithRedirect","linkWithRedirect","_linkWithRedirect","_getRedirectResult","resolverExtern","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","handled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","eventUid","_getProjectConfig","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","domain","currentUrl","hostname","URL","ceUrl","escapedDomainPattern","re","RegExp","matchDomain","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","H","hint","L","CP","loadGapi","loadGapiIframe","gapi","iframes","getContext","ontimeout","Iframe","cbName","js._generateCallbackName","js\r\n ._loadJS","cachedGApiLoader","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","height","aria-hidden","tabindex","EID_FROM_APIHOST","_openIframe","where","eid","fw","getIframeUrl","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","iframe","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","_open","screen","availHeight","availWidth","scrollbars","optionsString","reduce","accum","_isIOSStandalone","standalone","click","createEvent","initMouseEvent","dispatchEvent","openAsNewWindowIOS","newWin","focus","WIDGET_PATH","EMULATOR_WIDGET_PATH","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","tid","paramsDict","appCheckTokenFragment","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","initAndGetManager","register","iframeEvent","authEvent","send","PhoneMultiFactorAssertionImpl","_finalizeEnroll","_finalizeSignIn","_fromCredential","phoneVerificationInfo","PhoneMultiFactorGenerator","FACTOR_ID","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","updateProactiveRefresh","removeAuthTokenListener","_cordovaWindow","setAttribute","charset","deps","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","authInternalProvider","getVersionForPlatform","_generateHandlerUrl","BuildInfo","sessionDigest","TextEncoder","buff","ArrayBuffer","view","stringToArrayBuffer","subtle","arr","num","padStart","computeSha256","_performRedirect","handlerUrl","cordova","plugins","browsertab","isAvailable","browserTabIsAvailable","iabRef","openUrl","InAppBrowser","SESSION_ID_LENGTH","CordovaAuthEventManager","passiveListeners","initPromise","resolveInialized","addPassiveListener","removePassiveListener","resetRedirect","_generateNewEvent","idx","generateSessionId","_getAndRemoveEvent","persistenceKey","_eventFromPartialAndUrl","partialEvent","callbackUrl","searchParamsOrEmpty","iOSDoubleDeepLink","errorObject","parseJsonOrNull","cordovaPopupRedirectResolver","attachCallbackListeners","win","universalLinks","missingPlugin","_k","_j","eventListener","cleanup","onCloseTimer","authEventSeen","closeBrowserTab","resumed","visibilityChanged","visibilityState","_waitForAppResume","_cb","iosBundleId","handleOpenURL","noEventTimeout","generateNoEvent","universalLinksCb","eventData","finalEvent","existingHandleOpenURL","packagePrefix","_isAndroidOrIosCordovaScheme","_isLocalStorageNotSynchronized","_isEdge","_isWebStorageSupported","impl","_isPopupRedirectSupported","_isLikelyCordova","Persistence","LOCAL","NONE","SESSION","exp._assert","PERSISTENCE_KEY","_savePersistenceForRedirect","getSessionStorageIfAvailable","exp._persistenceKeyName","CompatPopupRedirectResolver","browserResolver","exp._getInstance","exp.browserPopupRedirectResolver","cordovaResolver","exp.cordovaPopupRedirectResolver","underlyingResolver","exp.browserSessionPersistence","exp._getRedirectResult","exp._overrideRedirectResult","selectUnderlyingResolver","assertedUnderlyingResolver","isCordova","timeoutId","attachExtraErrorFields","mfaErr","MultiFactorResolver","errorInternal","credentialFromObject","credErr","exp.PhoneAuthProvider","exp.ProviderId","exp.GoogleAuthProvider","exp.FacebookAuthProvider","exp.GithubAuthProvider","exp.TwitterAuthProvider","exp.SAMLAuthCredential","exp.OAuthCredential","exp.OAuthProvider","convertCredential","credentialPromise","additionalUserInfo","exp.getAdditionalUserInfo","User","getOrCreate","convertConfirmationResult","confirmationResultPromise","confirmationResultExp","wrapped","userModular","multiFactor","USER_MAP","linkAndRetrieveDataWithCredential","exp.linkWithCredential","appVerifier","exp.linkWithPhoneNumber","linkWithPopup","exp.linkWithPopup","exp._castAuth","exp.linkWithRedirect","reauthenticateAndRetrieveDataWithCredential","exp.reauthenticateWithCredential","reauthenticateWithPhoneNumber","exp.reauthenticateWithPhoneNumber","reauthenticateWithPopup","exp.reauthenticateWithPopup","exp.reauthenticateWithRedirect","exp.sendEmailVerification","exp.unlink","updateEmail","updatePassword","newPassword","updatePhoneNumber","phoneCredential","exp.updatePhoneNumber","exp.updateProfile","exp.verifyBeforeUpdateEmail","Auth","linkUnderlyingAuth","persistences","exp.inMemoryPersistence","exp.indexedDBLocalPersistence","_getPersistencesFromRedirect","exp.browserLocalPersistence","buildPersistenceHierarchy","exp.debugErrorMap","useEmulator","exp.connectAuthEmulator","exp.applyActionCode","exp.checkActionCode","confirmPasswordReset","account\r\n .resetPassword","exp.confirmPasswordReset","createUserWithEmailAndPassword","signUpResponse","exp.createUserWithEmailAndPassword","fetchProvidersForEmail","exp.fetchSignInMethodsForEmail","isSignInWithEmailLink","getRedirectResult","addFrameworkForLogging","wrapObservers","api.sendSignInLinkToEmail","exp.sendSignInLinkToEmail","authentication.sendPasswordResetEmail","exp.sendPasswordResetEmail","converted","isIndexedDBFullySupported","exp\r\n ._getInstance","exp._fail","signInAndRetrieveDataWithCredential","signInAnonymously","exp.signInAnonymously","exp.signInWithCredential","exp.signInWithCustomToken","signInWithEmailAndPassword","exp.signInWithEmailLink","exp.signInWithPhoneNumber","signInWithPopup","exp.signInWithPopup","exp.signInWithRedirect","verifyPasswordResetCode","exp.verifyPasswordResetCode","oldNext","exp.RecaptchaVerifier","authProvider","ActionCodeInfo","Operation","CompatAuthProvider","CompatRecaptchaVerifier","setSDKVersion","DOMStorageWrapper","domStorage_","prefix_","prefixedName_","storedVal","MemoryStorage","cache_","isInMemoryStorage","OperationType","createStoragefor","domStorageName","domStorage","sha1","high","low","sha1Bytes","PersistentStorage","SessionStorage","LUIDGenerator","buildLogMessage_","varArgs","firstLog_","logWrapper","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","dataSegs","enableLogging","logger_","persistent","fatal","warnIfPageIsSecure","isInvalidJSONNumber","POSITIVE_INFINITY","NEGATIVE_INFINITY","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","each","doubleToIEEE754String","ln","Infinity","abs","LN2","bits","hexByteString","hexByte","parseInt","INTEGER_REGEXP_","intVal","INTEGER_32_MIN","INTEGER_32_MAX","setTimeoutNonBlocking","Deno","unrefTimer","exceptionGuard","stack","AppCheckTokenProvider","appName_","appCheckProvider","addTokenChangeListener","notifyForInvalidToken","FirebaseAuthTokenProvider","firebaseOptions_","authProvider_","auth_","removeTokenChangeListener","EmulatorTokenProvider","OWNER","FORGE_DOMAIN_RE","WEBSOCKET","LONG_POLLING","RepoInfo","secure","webSocketOnly","nodeAdmin","includeNamespaceInQueryParams","isUsingEmulator","_host","_domain","internalHost","isCacheableHost","isCustomHost","newHost","toURLString","repoInfoConnectionURL","repoInfo","connURL","pairs","StatsCollection","counters_","incrementCounter","amount","collections","reporters","statsManagerGetCollection","hashString","PacketReceiver","onMessage_","pendingResponses","currentResponseNum","closeAfterResponse","onClose","closeAfter","responseNum","handleResponse","requestNum","toProcess","BrowserPollConnection","connId","applicationId","transportSessionId","lastSessionId","bytesSent","bytesReceived","everConnected_","log_","stats_","urlFn","onDisconnect","curSegmentNum","onDisconnect_","myPacketOrderer","isClosed_","connectTimeoutTimer_","onClosed_","called","wrappedFn","attachEvent","executeWhenDOMReady","scriptTagHolder","FirebaseIFrameScriptHolder","arg1","arg2","incrementIncomingBytes_","sendNewPolls","pN","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","Windows","UI","markConnectionHealthy","shutdown_","myDisconnFrame","dataStr","base64data","MAX_URL_DATA_SIZE","enqueueSegment","pw","dframe","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","currentDomain","iframeContents","doc","contentWindow","contentDocument","alive","textContent","myID","myPW","newRequest_","theURL","curDataString","theSeg","seg","ts","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","loadCB","newScript","onreadystatechange","rstate","parentNode","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","mySock","onopen","onclose","m","handleIncomingFrame","isOldAndroid","oldAndroidMatch","parseFloat","previouslyFailed","appendFrame_","jsonMess","fullMess","handleNewFrameCount_","frameCount","extractFrameCount_","mess","remainingData","resetKeepAlive","sendString_","responsesRequiredToBeHealthy","healthyTimeout","TransportManager","initTransports_","ALL_TRANSPORTS","IS_TRANSPORT_INITIALIZED","globalTransportInitialized_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports","transport","initialTransport","upgradeTransport","Connection","repoInfo_","applicationId_","appCheckToken_","authToken_","onReady_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","start_","conn","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeoutMS","healthyTimeout_","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","sendRequest","dataMsg","sendData_","tryCleanupConnection","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","onControl_","onDataMessage_","onPrimaryResponse_","handshakePayload","h","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","timestamp","onConnectionEstablished_","tryStartUpgrade_","startUpgrade_","closeConnections_","ServerActions","pathString","onComplete","hash","merge","refreshAppCheckToken","onDisconnectPut","onDisconnectMerge","onDisconnectCancel","reportStats","stats","EventEmitter","allowedEvents_","listeners_","trigger","on","validateEventType_","getInitialEvent","off","splice","et","OnlineMonitor","online_","getInstance","currentlyOnline","Path","pathOrString","pieceNum","pieces_","copyTo","pieceNum_","newEmptyPath","pathGetFront","pathGetLength","pathPopFront","pathGetBack","pathSlice","begin","pathParent","pieces","pathChild","childPathObj","childPieces","pathIsEmpty","newRelativePath","outerPath","innerPath","outer","inner","pathCompare","right","leftKeys","rightKeys","cmp","pathEquals","other","pathContains","ValidationPath","errorPrefix_","parts_","byteLength_","validationPathCheckValid","validationPath","validationPathToErrorString","VisibilityMonitor","hidden","visibilityChange","visible_","visible","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","appCheckTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens","outstandingPuts_","outstandingGets_","outstandingPutCount_","outstandingGetCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","establishConnectionTimer_","requestCBHash_","requestNumber_","realtime_","forceTokenRefresh_","invalidAuthTokenCount_","invalidAppCheckTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","onVisible_","onOnline_","onResponse","curReqNum","initConnection_","_path","q","_queryObject","sendGet_","listen","currentHashFn","queryId","_queryIdentifier","_queryParams","isDefault","loadsAllData","listenSpec","hashFn","sendListen_","req","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","getIndex","tryAuth","reduceReconnectDelayIfAdminCredential_","tryAppCheck","authMethod","isValidFormat","requestData","onAuthRevoked_","onAppCheckRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","errorReason","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","handleTimestamp_","sendConnectStats_","restoreState_","scheduleConnect_","establishConnection_","online","onRealtimeDisconnect_","reconnectDelay","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectAttempt","onDataMessage","onReady","nextConnectionId_","canceled","connection","closeFn","interrupt","resume","delta","serverTimeOffset","normalizedPathString","statusCode","explanation","queries","NamedNode","Wrap","Index","getCompare","compare","indexedValueChanged","oldNode","newNode","oldWrapped","newWrapped","minPost","MIN","__EMPTY_NODE","KeyIndex","isDefinedOn","maxPost","makePost","indexValue","KEY_INDEX","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","getNext","hasNext","peek","LLRBNode","RED","SortedMap","EMPTY_NODE","copy","count","inorderTraversal","reverseTraversal","min_","minKey","maxKey","insert","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","LLRBEmptyNode","comparator_","root_","getPredecessorKey","rightParent","getIterator","resultGenerator","getIteratorFrom","getReverseIteratorFrom","getReverseIterator","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","MAX_NODE","priorityHashText","priority","validatePriorityNode","priorityNode","isLeafNode","getPriority","__childrenNodeConstructor","LeafNode","value_","priorityNode_","lazyHash_","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","hasChild","getPredecessorChildName","childNode","updateImmediateChild","newChildNode","updateChild","front","numChildren","forEachChild","exportFormat",".value","getValue",".priority","toHash","compareTo","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","withIndex","isIndexed","equals","nodeFromJSON","PRIORITY_INDEX","aPriority","bPriority","indexCmp","LOG_2","Base12Num","current_","mask","bits_","nextBitIsOne","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","namedNode","middle","root","base12","buildPennant","chunkSize","childTree","pennant","attachPennant","isOne","buildFrom12Array","_defaultIndexMap","fallbackObject","IndexMap","indexes_","indexSet_","Default","indexKey","sortedMap","hasIndex","indexDefinition","addIndex","existingChildren","sawIndexedValue","iter","newIndex","indexName","newIndexSet","newIndexes","addToIndexes","indexedChildren","existingSnap","newChildren","removeFromIndexes","ChildrenNode","children_","indexMap_","child","newIndexMap","newPriority","newImmediateChild","numKeys","allIntegerKeys","childHash","resolveIndex_","predecessor","getFirstChildName","getFirstChild","getLastChildName","getLastChild","wrappedNode","startPost","iterator","endPost","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","defineProperties","MAX","USE_HINZE","jsonLeaf","childData","children","childrenHavePriority","childSet","sortedChildSet","PathIndex","indexPath_","extractChild","snap","aChild","bChild","valueNode","VALUE_INDEX","changeValue","snapshotNode","changeChildAdded","changeChildRemoved","changeChildChanged","oldSnap","IndexedFilter","index_","newChild","affectedPath","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","startIsInclusive_","startAfterSet_","endIsInclusive_","endBeforeSet_","getStartPost","getEndPost","isWithinStart","isWithinEnd","filtered","hasStart","startName","getIndexStartName","getIndexStartValue","hasEnd","endName","getIndexEndName","getIndexEndValue","LimitedFilter","withinDirectionalStart","reverse_","withinEndPost","withinStartPost","withinDirectionalEnd","compareRes","rangedFilter_","limit_","getLimit","isViewFromLeft","fullLimitUpdateChild_","childKey","childSnap","changeAccumulator","oldEventCache","newChildNamedNode","windowBoundary","inRange","oldChildSnap","nextChild","getChildAfterChild","compareNext","newEventCache","QueryParams","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","hasLimit","hasAnchoredLimit","queryParamsStartAt","queryParams","newParams","queryParamsEndAt","queryParamsOrderBy","queryParamsToRestQueryStringParameters","qs","orderBy","endParam","startParam","queryParamsGetQueryObject","viewFrom","ReadonlyRestClient","listens_","getListenId_","listenId","thisListen","queryStringParameters","restRequest_","xhr","XMLHttpRequest","responseText","SnapshotHolder","rootNode_","getNode","updateSnapshot","newSnapshotNode","newSparseSnapshotTree","sparseSnapshotTreeRemember","sparseSnapshotTree","sparseSnapshotTreeForEachTree","prefixPath","tree","StatsListener","collection_","last_","newStats","stat","StatsReporter","collection","server_","statsToReport_","statsListener_","reportStats_","reportedStats","haveStatsToReport","newOperationSourceUser","fromUser","fromServer","tagged","newOperationSourceServer","newOperationSourceServerTaggedQuery","AckUserWrite","affectedTree","revert","ACK_USER_WRITE","operationForChild","subtree","ListenComplete","LISTEN_COMPLETE","Overwrite","OVERWRITE","Merge","MERGE","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","EventGenerator","query_","eventGeneratorGenerateEventsForChanges","eventGenerator","changes","eventCache","eventRegistrations","events","moves","change","eventGeneratorGenerateEventsForType","registrations","filteredChanges","aWrapped","bWrapped","eventGeneratorCompareChanges","materializedChange","prevName","registration","respondsTo","newViewCache","serverCache","viewCacheUpdateEventSnap","viewCache","eventSnap","viewCacheUpdateServerSnap","serverSnap","viewCacheGetCompleteEventSnap","viewCacheGetCompleteServerSnap","emptyChildrenSingleton","ImmutableTree","fromObject","childPath","findRootMostMatchingPathAndValue","relativePath","predicate","childExistingPathAndValue","findRootMostValueAndPath","toSet","setTree","newTree","fold","fold_","pathSoFar","findOnPath","findOnPath_","pathToFollow","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","CompoundWrite","writeTree_","empty","compoundWriteAddWrite","compoundWrite","rootmost","rootMostPath","newWriteTree","compoundWriteAddWrites","newWrite","compoundWriteRemoveWrite","compoundWriteHasCompleteWrite","compoundWriteGetCompleteNode","compoundWriteGetCompleteChildren","compoundWriteChildCompoundWrite","shadowingNode","compoundWriteIsEmpty","compoundWriteApply","applySubtreeWrite","writeTree","priorityWrite","writeTreeChildWrites","newWriteTreeRef","writeTreeRemoveWrite","writeId","allWrites","findIndex","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","writeRecord","writeTreeRecordContainsPath_","visibleWrites","writeTreeLayerTree_","writeTreeDefaultFilter_","lastWriteId","writes","treeRoot","writePath","deepNode","writeTreeCalcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","subMerge","writeTreeRefCalcCompleteEventCache","writeTreeRef","writeTreeRefCalcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","writeTreeCalcCompleteEventChildren","writeTreeRefCalcEventCacheAfterServerOverwrite","existingEventSnap","existingServerSnap","childMerge","writeTreeCalcEventCacheAfterServerOverwrite","writeTreeRefShadowingWrite","writeTreeRefCalcIndexedSlice","completeServerData","toIterate","nodes","writeTreeCalcIndexedSlice","writeTreeRefCalcCompleteChild","existingServerCache","writeTreeRefChild","ChildChangeAccumulator","changeMap","oldChange","oldType","getChanges","NO_COMPLETE_CHILD_SOURCE","getCompleteChild","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","viewProcessorApplyOperation","viewProcessor","oldViewCache","writesCache","completeCache","accumulator","filterServerNode","viewProcessorApplyUserOverwrite","viewProcessorApplyServerOverwrite","changedChildren","curViewCache","viewProcessorCacheHasChild","viewProcessorApplyUserMerge","viewProcessorApplyServerMerge","ackUserWrite","serverChildren","viewProcessorRevertUserWrite","ackPath","mergePath","serverCachePath","viewProcessorAckUserWrite","oldServerNode","viewProcessorGenerateEventCacheAfterServerEvent","viewProcessorListenComplete","isLeafOrEmpty","oldCompleteSnap","viewProcessorMaybeAddValueEvent","changePath","oldEventSnap","completeEventChildren","completeNode","oldEventNode","updatedPriority","childChangePath","newEventChild","eventChildUpdate","changedSnap","oldServerSnap","newServerCache","serverFilter","newServerNode","viewProcessorApplyMerge","viewMergeTree","childMergeTree","isUnknownDeepMerge","View","initialViewCache","eventRegistrations_","indexFilter","processor_","initialServerCache","initialEventCache","eventGenerator_","viewIsEmpty","viewRemoveEventRegistration","eventRegistration","cancelError","cancelEvents","maybeEvent","createCancelEvent","remaining","hasAnyCallback","concat","viewApplyOperation","viewGenerateEventsForChanges_","referenceConstructor","SyncPoint","views","syncPointApplyOperation","syncPoint","optCompleteServerCache","syncPointGetView","serverCacheComplete","eventCacheComplete","syncPointAddEventRegistration","initialChanges","eventNode","viewGetInitialEvents","syncPointRemoveEventRegistration","removed","hadCompleteView","syncPointHasCompleteView","viewQueryId","_repo","syncPointGetQueryViews","syncPointGetCompleteServerCache","cache","viewGetCompleteServerCache","syncPointViewForQuery","syncPointGetCompleteView","syncPointViewExistsForQuery","syncTreeNextQueryTag_","SyncTree","listenProvider_","syncPointTree_","pendingWriteTree_","tagToQueryMap","queryToTagMap","syncTreeApplyUserOverwrite","syncTree","syncTreeApplyOperationToSyncPoints_","syncTreeApplyUserMerge","changeTree","syncTreeAckUserWrite","record","writeTreeGetWrite","syncTreeApplyServerOverwrite","syncTreeRemoveEventRegistration","skipListenerDedup","maybeSyncPoint","removedAndEvents","removingDefault","covered","parentSyncPoint","newViews","maybeChildSyncPoint","childMap","childViews","newQuery","syncTreeCreateListenerForView_","startListening","syncTreeQueryForListening_","syncTreeTagForQuery","stopListening","tagToRemove","syncTreeMakeQueryKey_","queryToRemove","removedQuery","removedQueryKey","removedQueryTag","syncTreeRemoveTags_","syncTreeApplyTaggedQueryOverwrite","queryKey","syncTreeQueryKeyForTag_","syncTreeParseQueryKey_","queryPath","syncTreeApplyTaggedOperation_","syncTreeAddEventRegistration","skipSetupListener","foundAncestorDefaultView","pathToSyncPoint","sp","childSyncPoint","viewAlreadyExists","queriesToStop","childQueries","queryToStop","syncTreeSetupListener_","syncTreeCalcCompleteEventCache","syncTreeGetServerValue","serverCacheNode","syncTreeApplyOperationHelper_","syncPointTree","syncTreeApplyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","syncTreeApplyTaggedListenComplete","toUpperCase","errorForServerCode","splitIndex","ExistingValueProvider","DeferredValueProvider","syncTree_","path_","generateWithValues","resolveDeferredLeafValue","existingVal","serverValues","resolveScalarDeferredValue","resolveComplexDeferredValue","unused","existingNode","leaf","resolveDeferredValueTree","resolveDeferredValue","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","Tree","parent","childCount","treeSubTree","pathObj","treeGetValue","treeSetValue","treeUpdateParents","treeHasChildren","treeForEachChild","treeGetPath","childEmpty","childExists","treeIsEmpty","validateFirebaseDataArg","validateFirebaseData","errorPrefixFxn","validateFirebaseMergeDataArg","mergePaths","curPath","isValidPriority","isValidKey","prevPath","validateFirebaseMergePaths","validatePriority","validateKey","validateRootPathString","validatePathString","validateWritablePath","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidPathString","isValidRootPathString","hasDotValue","hasActualChild","last","validateUrl","parsedUrl","EventQueue","eventLists_","recursionDepth_","eventQueueQueueEvents","eventQueue","eventDataList","currList","getPath","eventQueueRaiseEventsAtPath","eventQueueRaiseQueuedEventsMatchingPredicate","eventPath","eventQueueRaiseEventsForChangedPath","changedPath","sentAll","eventList","eventFn","getEventRunner","eventListRaise","INTERRUPT_REASON","MAX_TRANSACTION_RETRIES","Repo","forceRestClient_","appCheckProvider_","dataUpdateCount","eventQueue_","nextWriteId_","interceptServerDataCallback_","transactionQueueTree_","persistentConnection_","repoStart","repo","authOverride","search","beingCrawled","isMerge","repoOnDataUpdate","repoOnConnectStatus","connectStatus","repoUpdateInfo","statsReporter_","creatorFunction","infoData_","infoSyncTree_","infoEvents","serverSyncTree_","repoServerTime","offsetNode","repoGenerateServerValues","taggedSnap","taggedChildren","raw","syncTreeApplyTaggedQueryMerge","repoRerunTransactions","repoLog","resolvedOnDisconnectTree","resolved","repoAbortTransactions","repoRunOnDisconnectEvents","repoGetNextWriteId","repoSetWithPriority","newVal","newNodeUnresolved","clearEvents","repoCallOnCompleteCallback","repoOnDisconnectCancel","sparseSnapshotTreeForget","repoOnDisconnectSet","repoRemoveEventCallbackForQuery","repoInterrupt","repoGetLatestState","excludeSets","repoSendReadyTransactions","repoPruneCompletedTransactionsBelowNode","repoBuildTransactionQueue","every","setsToIgnore","txn","currentWriteId","latestState","snapToSend","latestHash","retryCount","currentOutputSnapshotRaw","dataToSend","pathToSend","currentOutputSnapshotResolved","unwatcher","abortReason","repoSendTransactionQueue","rootMostTransactionNode","repoGetAncestorTransactionNode","txnsToRerun","abortTransaction","currentNode","currentInputSnapshot","newDataNode","oldWriteId","newNodeResolved","applyLocally","repoRerunTransactionQueue","transactionNode","transactionQueue","repoAggregateTransactionQueuesForNode","nodeQueue","order","to","includeSelf","treeForEachAncestor","repoAbortTransactionsOnNode","treeForEachDescendant","childrenFirst","lastSent","parseRepoInfo","dataURL","parseDatabaseURL","scheme","subdomain","colonInd","slashInd","questionMarkInd","pathStringDecoded","piece","decodePath","dotInd","queryString","segment","kv","decodeQuery","hostWithoutPort","PUSH_CHARS","nextPushId","lastPushTime","lastRandChars","duplicateTime","timeStampChars","DataEvent","snapshot","ref","getEventType","exportVal","CancelEvent","CallbackContext","snapshotCallback","cancelCallback","onValue","expDataSnapshot","previousChildName","onCancel","hasCancelCallback","userCallback","OnDisconnect","setWithPriority","repoOnDisconnectSetWithPriority","childrenToMerge","repoOnDisconnectUpdate","QueryImpl","_orderByCalled","ReferenceImpl","sameRepo","samePath","sameQueryIdentifier","pathToUrlEncodedString","validateNoPreviousOrderByCall","validateQueryEndpoints","startNode","endNode","tooManyArgsError","wrongArgTypeError","validateLimit","parentPath","DataSnapshot","_node","_index","childRef","exists","hasChildren","_checkNotDeleted","_root","refFromURL","parsedURL","changedKey","changedValue","repoUpdate","callbackContext","ValueEventRegistration","cached","ChildEventRegistration","eventToCheck","cancelCallbackOrListenOptions","onlyOnce","onceCallback","dataSnapshot","repoAddEventCallbackForQuery","onChildAdded","onChildChanged","onChildMoved","onChildRemoved","expCallback","QueryConstraint","QueryEndAtConstraint","_value","_apply","QueryEndBeforeConstraint","queryParamsEndBefore","QueryStartAtConstraint","QueryStartAfterConstraint","queryParamsStartAfter","QueryLimitToFirstConstraint","_limit","newLimit","queryParamsLimitToFirst","QueryLimitToLastConstraint","queryParamsLimitToLast","QueryOrderByChildConstraint","parsedPath","QueryOrderByKeyConstraint","QueryOrderByPriorityConstraint","QueryOrderByValueConstraint","QueryEqualToValueConstraint","queryConstraints","queryImpl","constraint","FIREBASE_DATABASE_EMULATOR_HOST_VAR","repos","useRestClient","repoManagerDatabaseFromApp","dbUrl","databaseURL","isEmulator","dbEmulatorHost","authTokenProvider","appRepos","repoManagerCreateRepo","Database","_repoInternal","_instanceStarted","_rootInternal","repoManagerDeleteRepo","apiName","checkTransportInit","forceWebSockets","forceLongPolling","connectDatabaseEmulator","tokenProvider","mockUserToken","goOnline","enableLoggingImpl","SERVER_TIMESTAMP",".sv","TransactionResult","committed","runTransaction","transactionUpdate","currentState","queueNode","priorityForNode","repoStartTransaction","simpleListen","echo","onEcho","objectToMerge","newObjectToMerge","_database","_validatePathString","getRef","Reference","Query","database","cancelCallbackOrContext","ret","getCancelAndContextArgs_","valueCallback","expSnapshot","validateEventType","once","failureCallbackOrContext","limitToFirst","limit","limitToLast","orderByChild","orderByKey","orderByPriority","orderByValue","startAt","startAfter","endAt","endBefore","equalTo","cancelOrContext","_ReferenceImpl","_QueryImpl","_QueryParams","getParent","getRoot","_validateWritablePath","bool","validateBoolean","transactionResult","setPriority","expPromise","thennablePushRef","pushRef","expRef","ModularOnDisconnect","goOffline","ServerValue","TIMESTAMP","increment","customAuthImpl","customAppCheckImpl","_setSDKVersion","_repoManagerDatabaseFromApp","databaseExp","goog","goog.global","goog.isArrayLike","aa","goog.isObject","goog.UID_PROPERTY_","goog.uidCounter_","goog.bindNative_","ea","selfObj","var_args","goog.bindJs_","fa","boundArgs","newArgs","unshift","goog.bind","goog.bindapply","goog.partial","ha","goog.inherits","childCtor","parentCtor","tempCtor","superClass_","childCtor.base","me","methodName","goog.Disposable","disposed_","onDisposeCallbacks_","dispose","goog.Disposable.prototype.dispose","goog.getUid","disposeInternal","goog.Disposable.MONITORING_MODE","goog.Disposable.prototype.disposeInternal","opt_fromIndex","fromIndex","toArray","rv","extend","arr1","arr2","len1","len2","goog.events.Event","w","opt_target","currentTarget","defaultPrevented","preventDefault","goog.events.Event.prototype.preventDefault","PASSIVE_EVENTS","goog.globaladdEventListener","passive","nullFunction","goog.globalremoveEventListener","goog.string.internal.isEmptyOrWhitespace","x","getNativeUserAgentString","pa","goog.globalnavigator","matchUserAgent","y","goog.reflect.sinkValue","qa","goog.userAgent.VERSION","goog.userAgent.OPERA","goog.userAgent.IE","goog.userAgent.EDGE","goog.userAgent.EDGE_OR_IE","goog.userAgent.GECKO","subString","goog.userAgent.WEBKIT","ya","docMode","goog.userAgent.getDocumentMode_","za","goog.userAgent.DOCUMENT_MODE","goog.events.BrowserEvent","A","opt_e","opt_currentTarget","goog.events.Eventcall","goog.events.BrowserEvent.base","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","event_","relevantTouch","changedTouches","srcElement","nodeName","MOUSEOVER","fromElement","MOUSEOUT","toElement","pageX","pageY","goog.events.BrowserEvent.IE_POINTER_TYPE_MAP","goog.events.BrowserEventsuperClass_preventDefaultcall","2","TOUCH","3","PEN","4","MOUSE","goog.events.BrowserEvent.prototype.preventDefault","be","returnValue","goog.events.Listenable.IMPLEMENTED_BY_PROP","goog.events.ListenableKey.counter_","goog.events.Listener","capture","opt_handler","callOnce","goog.events.Listener.prototype.markAsRemoved","opt_obj","clone","PROTOTYPE_FIELDS","goog.events.ListenerMap","Sa","typeCount_","Ua","goog.events.ListenerMap.prototype.removeByKey","markAsRemoved","goog.events.ListenerMap.findListenerIndex_","Ta","listenerArray","opt_useCapture","opt_listenerScope","listenerObj","goog.events.ListenerMap.prototype.add","typeStr","goog.events.LISTENER_MAP_PROP_","goog.events.onStringMap_","goog.events.listen","opt_options","goog.events.listenOnce","Za","goog.events.wrapListener","listenOnce","goog.events.listen_","ab","listenerMap","goog.events.getListenerMap_","goog.events.getProxy","proxyCallbackFunction","goog.events.handleBrowserEvent_","eventObject","goog.events.BrowserFeature.PASSIVE_EVENTS","goog.events.getOnString_","addListener","removeListener","goog.events.unlistenByKey","gb","removeByKey","eventTargetListeners_","detachEvent","Wa","goog.events.onString_","eb","opt_evt","listenerFn","listenerHandler","bb","goog.events.LISTENER_WRAPPER_PROP_","$a","goog.events.EventTarget","B","goog.Disposablecall","actualEventTarget_","parentEventTarget_","C","goog.events.EventTarget.prototype.dispatchEvent","ancestorsTree","ancestor","getParentEventTarget","oldEvent","Ra","opt_ancestorsTree","fireListeners","ib","goog.events.EventTarget.prototype.fireListeners","unlistenByKey","goog.events.EventTarget.prototype.removeEventListener","opt_capture","opt_handlerScope","goog.events.unlisten","fb","goog.events.EventTarget.prototype.disposeInternal","goog.events.EventTargetsuperClass_disposeInternalcall","removeAllListeners","goog.events.EventTarget.prototype.listen","goog.events.EventTarget.prototype.listenOnce","goog.json.serialize","module$contents$goog$async$WorkQueue_WorkQueue.freelist_","create_","reset_","occupants_","head_","item","WorkItem","pb","workQueueScheduled","workQueue","workTail_","workHead_","module$contents$goog$async$WorkQueue_WorkQueue.freelist_get","initializeRunner","goog.globalPromiseresolve","module$contents$goog$async$run_run.processWorkQueue","throwException","exception","goog.globalsetTimeout","module$contents$goog$async$WorkQueue_WorkQueue.freelist_put","module$contents$goog$async$WorkQueue_WorkQueue.DEFAULT_MAX_UNUSED","goog.Timer","wb","opt_interval","opt_timerObject","goog.events.EventTargetcall","interval_","timerObject_","boundTick_","tick_","xb","goog.Timer.prototype.stop","timer_","goog.Timer.callOnce","yb","opt_delay","JSC$2177_enabled","JSC$2177_timer_","goog.Timer.prototype","goog.Timer.prototype.tick_","elapsed","goog.Timer.intervalScale","dispatchTick","goog.Timer.TICK","goog.Timer.prototype.start","goog.Timer.prototype.disposeInternal","goog.TimersuperClass_disposeInternalcall","Throttle","listener_","args_","shouldFire_","fire","doAction_","zb","onTimer_","goog.globalclearTimeout","goog.events.EventHandler","Bb","opt_scope","handler_","keys_","goog.events.EventHandler.typeArray_","Eb","goog.events.EventHandler.prototype.listen_","opt_fn","goog.events.EventHandler.prototype.removeAll","Fb","goog.labs.net.webChannel.WebChannelDebug","Gb","redactEnabled_","WebChannelDebug.prototype.xmlHttpChannelResponseText","D","opt_desc","WebChannelDebug.prototype.redactResponse_","responseArray","dataPart","redactResponse_","goog.events.EventHandler.prototype.disposeInternal","goog.events.EventHandlersuperClass_disposeInternalcall","removeAll","goog.events.EventHandler.prototype.handleEvent","disableRedact","WebChannelDebug.prototype.disableRedact","WebChannelDebug.prototype.info","goog.labs.net.webChannel.requestStats.Event","goog.labs.net.webChannel.requestStats.eventTarget_","Mb","Lb","Nb","goog.labs.net.webChannel.requestStats.EventSERVER_REACHABILITY_EVENT","SERVER_REACHABILITY_EVENT","requestStats.notifyServerReachabilityEvent","Ob","goog.labs.net.webChannel.requestStats.getStatEventTarget_","goog.labs.net.webChannel.requestStats.ServerReachabilityEvent","Pb","goog.labs.net.webChannel.requestStats.EventSTAT_EVENT","STAT_EVENT","requestStats.notifyStatEvent","goog.labs.net.webChannel.requestStats.StatEvent","Qb","goog.labs.net.webChannel.requestStats.EventTIMING_EVENT","TIMING_EVENT","Rb","goog.labs.net.webChannel.requestStats.TimingEvent","goog.net.ErrorCode","NO_ERROR","ACCESS_DENIED","FILE_NOT_FOUND","FF_SILENT_ERROR","CUSTOM_ERROR","EXCEPTION","HTTP_ERROR","ABORT","TIMEOUT","OFFLINE","goog.net.EventType","COMPLETE","SUCCESS","READY","READY_STATE_CHANGE","INCREMENTAL_DATA","PROGRESS","DOWNLOAD_PROGRESS","UPLOAD_PROGRESS","goog.net.XmlHttpFactory","Ub","goog.net.XmlHttpFactory.prototype.getOptions","Vb","cachedOptions_","internalGetOptions","goog.net.WebChannel","Wb","goog.net.WebChannel.EventType","OPEN","CLOSE","MESSAGE","goog.net.WebChannel.MessageEvent","Yb","goog.net.WebChannel.MessageEvent.base","goog.net.WebChannel.ErrorEvent","Zb","goog.net.WebChannel.ErrorEvent.base","goog.net.DefaultXmlHttpFactory","ac","goog.labs.net.webChannel.ChannelRequest","bc","channelDebug","opt_requestId","opt_retryId","channel_","channelDebug_","rid_","retryId_","eventHandler_","timeout_","goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_","pollingTimer_","EDGE_POLLING_INTERVAL_","extraHeaders_","successful_","postData_","requestUri_","baseUri_","type_","requestStartTime_","watchDogTimeoutTime_","watchDogTimerId_","pendingMessages_","xmlHttp_","xmlHttpChunkStart_","lastError_","verb_","lastStatusCode_","cancelled_","readyStateChangeThrottleMs_","readyStateChangeThrottle_","firstByteReceived_","initialResponseDecoded_","decodeInitialResponse_","decodeChunks_","fetchResponseState_","goog.labs.net.webChannel.FetchResponseState","dc","textDecoder","responseBuffer","responseArrivedForFetch","createInstance","goog.net.DefaultXmlHttpFactory.prototype.createInstance","goog.net.DefaultXmlHttpFactory.prototype.internalGetOptions","goog.net.XmlHttp.factory_","goog.labs.net.webChannel.ChannelRequest.INVALID_CHUNK_","goog.labs.net.webChannel.ChannelRequest.INCOMPLETE_CHUNK_","gc","ChannelRequest.prototype.xmlHttpPost","uri","postData","XML_HTTP","makeUnique","decodeChunks","sendXmlHttp_","ChannelRequest.prototype.sendXmlHttp_","ic","hostPrefix","jc","ensureWatchDogTimer_","WebChannelDebug.prototype.xmlHttpChannelRequest","verb","attempt","kc","queryData_","useSecondaryDomains","supportsCrossDomainXhrs_","createXhrIo","xmlHttpHandler_","readyStateChangeHandler_","goog.labs.net.webChannel.requestStats.notifyServerReachabilityEvent","keyParts","keyValue","ChannelRequest.prototype.useFetchStreamsForResponse_","CLOSE_REQUEST","usesFetchStreams_","ChannelRequest.prototype.decodeNextChunks_","rc","decodeNextChunksSuccessful","chunkText","sizeEndIndex","sizeStartIndex","ChannelRequest.prototype.getNextChunk_","getNextChunk_","chunkStartIndex","BAD_DATA","goog.labs.net.webChannel.requestStats.notifyStatEvent","REQUEST_INCOMPLETE_DATA","xmlHttpChannelResponseText","F","REQUEST_BAD_DATA","safeOnRequestData_","useFetchStreamsForResponse_","NO_DATA","REQUEST_NO_DATA","backChannelRequest_","detectBufferingProxy_","bpDetectionDone_","clearBpDetectionTimer_","NOPROXY","cleanup_","dispatchFailure_","ChannelRequest.prototype.ensureWatchDogTimer_","wc","startWatchDogTimer_","ChannelRequest.prototype.startWatchDogTimer_","goog.labs.net.webChannel.requestStats.setTimeout","onWatchDogTimeout_","ChannelRequest.prototype.cancelWatchDogTimer_","nc","pc","ChannelRequest.prototype.dispatchFailure_","CLOSED","onRequestComplete","ChannelRequest.prototype.cleanup_","I","cancelWatchDogTimer_","xmlhttp","ChannelRequest.prototype.safeOnRequestData_","hasRequest","forwardChannelRequestPool_","OPENED","wireCodec_","parser_","ex","responseValues","handlePostResponse_","backChannelTimerId_","goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE","clearDeadBackchannelTimer_","cancelBackChannelRequest_","Ac","BACKCHANNEL_MISSING","lastPostResponseArrayId_","lastArrayId_","goog.labs.net.webChannel.WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF","enableStreaming_","backChannelRetryCount_","deadBackChannelTimerId_","onBackChannelDead_","getRequestCount","onForwardChannelFlushed_","forwardChannelFlushedCallback_","signalError_","BAD_RESPONSE","respArray","nextArray","onInput_","OPENING","sid_","hostPrefix_","negotiatedVersion","channelVersion_","negotiatedServerVersion","serverVersion_","httpSessionIdHeader","serverKeepaliveMs","Ka","backChannelRequestTimeoutMs_","applyControlHeaders_","clientProtocol","xhr_","getResponseHeader","goog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL","requestPool_","maxSize_","maxPoolSizeConfigured_","request_","addRequest","getHttpSessionIdParam","httpSessionIdParam_","goog.net.WebChannel.X_HTTP_SESSION_ID","setHttpSessionId","httpSessionId_","setParameterValue","forwardChannelUri_","channelOpened","handshakeRttMs_","startBackchannelAfterHandshake_","backChannelUri_","createDataUri","getBackChannelUri","removeRequest","opt_timeout","ensureBackChannel_","outgoingMaps_","ensureForwardChannel_","STOP","disconnect","channelHandleArray","goog.structs.forEach","Kc","col","goog.structs.getKeys","getKeys","getValues","l","goog.structs.getValues","ChannelRequest.prototype.setTimeout","goog.labs.net.webChannel.ChannelRequest.prototype","ChannelRequest.prototype.readyStateChangeHandler_","evt","throttle","INTERACTIVE","getReadyState","ChannelRequest.prototype.xmlHttpHandler_","onXmlHttpReadyStateChanged_","errorCode","getLastErrorCode","getStatus","getResponseText","responseChunks","responseLength","requestCompleted","TextDecoder","goog.globalTextDecoder","stream","WebChannelDebug.prototype.xmlHttpChannelResponseMetaData","goog.net.WebChannel.X_HTTP_INITIAL_RESPONSE","initialResponse","UNKNOWN_SESSION_ID","REQUEST_UNKNOWN_SESSION_ID","decodeNextChunks_","listen_","pollResponse_","goog.net.XhrIo.prototype.getResponseHeaders","headersObject","headersArray","getAllResponseHeaders","LOADED","goog.string.splitLimit","separator","returnVal","trim","STATUS","REQUEST_BAD_STATUS","ChannelRequest.prototype.pollResponse_","ChannelRequest.prototype.cancel","ChannelRequest.prototype.onWatchDogTimeout_","WebChannelDebug.prototype.timeoutResponse","handleTimeout_","REQUEST_TIMEOUT","goog.uri.utils.splitRe_","goog.Uri","M","opt_uri","domain_","userInfo_","scheme_","port_","fragment_","ignoreCase_","Nc","setScheme","setDomain","Oc","setPort","goog.Uri.QueryData","encodedQuery_","keyMap_","count_","setQueryData","setFragment","SCHEME","setUserInfo","goog.Uri.decodeOrEmpty_","USER_INFO","DOMAIN","PORT","setPath","PATH","QUERY_DATA","FRAGMENT","goog.Uri.prototype.clone","G","goog.Uri.prototype.setScheme","newScheme","opt_decode","goog.Uri.prototype.setPort","newPort","goog.Uri.prototype.setQueryData","Qc","queryData","goog.Uri.QueryData.prototype.setIgnoreCase","ignoreCase","ensureKeyMapInitialized_","invalidateCache_","lowerCase","setValues","goog.Uri.encodeSpecialChars_","goog.Uri.reDisallowedInQuery_","goog.Uri.prototype.setParameterValue","K","goog.Uri.prototype.makeUnique","RANDOM","opt_preserveReserved","decodeURI","Sc","unescapedPart","extra","opt_removeDoubleEncoding","encoded","encodeURI","goog.Uri.encodeChar_","Zc","ch","goog.Uri.prototype.toString","getScheme","goog.Uri.reDisallowedInSchemeOrUserInfo_","getDomain","getUserInfo","getPort","hasDomain","goog.Uri.reDisallowedInAbsolutePath_","goog.Uri.reDisallowedInRelativePath_","getEncodedQuery","fragment","getFragment","goog.Uri.reDisallowedInFragment_","Pc","opt_query","opt_ignoreCase","goog.Uri.QueryData.prototype.ensureKeyMapInitialized_","N","encodedQuery","indexOfEquals","goog.uri.utils.parseQueryData","$c","goog.Uri.QueryData.prototype.remove","getKeyName_","goog.Uri.QueryData.prototype.containsKey","ad","goog.Uri.QueryData.prototype.setValues","goog.Uri.QueryData.prototype.getKeyName_","O","goog.Uri.QueryData.prototype.add","goog.Uri.QueryData.prototype","goog.Uri.QueryData.prototype.forEach","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","goog.labs.net.webChannel.Wire.QueuedMap","mapId","ForwardChannelRequestPool","cd","opt_maxPoolSize","goog.globalPerformanceNavigationTiming","PerformanceNavigationTiming","entrys","goog.globalperformancegetEntriesByType","performance","getEntriesByType","nextHopProtocol","goog.globalchrome","goog.globalchromeloadTimes","loadTimes","wasFetchedViaSpdy","ed","ForwardChannelRequestPool.prototype.isFull","ForwardChannelRequestPool.prototype.getRequestCount","Bc","ForwardChannelRequestPool.prototype.hasRequest","ForwardChannelRequestPool.prototype.addRequest","Cc","ForwardChannelRequestPool.prototype.removeRequest","ForwardChannelRequestPool.prototype.getPendingMessages","fd","ma","ForwardChannelRequestPool.prototype.cancel","getPendingMessages","retValue","goog.json.NativeJsonProcessor","opt_replacer","opt_reviver","goog.labs.net.webChannel.WireV8","hd","netUtils.imageCallback_","kd","img","debugText","onabort","goog.net.FetchXmlHttpFactory","ld","worker_","worker","streamBinaryChunks_","streamBinaryChunks","md","goog.net.FetchXmlHttp.base","credentialsMode_","goog.net.FetchXmlHttp.RequestState.UNSENT","responseType","statusText","requestHeaders_","responseHeaders_","method_","url_","inProgress_","textDecoder_","currentReader_","fetchResponse_","goog.net.FetchXmlHttpFactory.prototype.createInstance","goog.net.FetchXmlHttp","UNSENT","goog.net.FetchXmlHttp.prototype.readInputFromFetch_","handleDataFromStream_","handleSendFailure_","goog.net.FetchXmlHttp.prototype.requestDone_","DONE","od","dispatchCallback_","goog.net.FetchXmlHttp.prototype.dispatchCallback_","goog.net.FetchXmlHttp.prototype.open","goog.net.FetchXmlHttp.prototype","goog.net.FetchXmlHttp.prototype.send","opt_data","requestInit","credentials","Request","handleResponse_","goog.net.FetchXmlHttp.prototype.abort","requestDone_","goog.net.FetchXmlHttp.prototype.handleResponse_","HEADER_RECEIVED","LOADING","arrayBuffer","handleResponseArrayBuffer_","ReadableStream","getReader","readInputFromFetch_","text","handleResponseText_","goog.net.FetchXmlHttp.prototype.handleDataFromStream_","dataPacket","newText","goog.net.FetchXmlHttp.prototype.handleResponseText_","goog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_","responseArrayBuffer","goog.net.FetchXmlHttp.prototype.handleSendFailure_","setRequestHeader","goog.net.FetchXmlHttp.prototype.setRequestHeader","goog.net.FetchXmlHttp.prototype.getResponseHeader","goog.net.FetchXmlHttp.prototype.getAllResponseHeaders","lines","pair","getCredentialsMode","setCredentialsMode","goog.json.hybrid.parse","goog.net.XhrIo","P","opt_xmlHttpFactory","goog.net.XhrIo.base","xmlHttpFactory_","active_","xhrOptions_","lastUri_","lastErrorCode_","inAbort_","inOpen_","inSend_","errorDispatched_","timeoutInterval_","timeoutId_","responseType_","goog.net.XhrIo.ResponseType.DEFAULT","useXhr2Timeout_","withCredentials_","DEFAULT","goog.net.XhrIo.HTTP_SCHEME_PATTERN","goog.net.XhrIo.METHODS_WITH_FORM_DATA","goog.net.XhrIo.prototype.error_","vd","dispatchErrors_","cleanUpXhr_","goog.net.XhrIo.prototype.dispatchErrors_","yd","Ad","goog.net.XhrIo.prototype.onReadyStateChangeHelper_","LOCAL_REQUEST_ERROR","onReadyStateChange_","isComplete","isSuccess","OK","CREATED","ACCEPTED","NO_CONTENT","PARTIAL_CONTENT","NOT_MODIFIED","QUIRK_IE_NO_CONTENT","goog.globalself","goog.globalselflocation","goog.globalselflocationprotocol","goog.net.XhrIo.HTTP_SCHEME_PATTERNtest","getStatusText","goog.net.XhrIo.prototype.cleanUpXhr_","opt_fromDispose","cleanUpTimeoutTimer_","clearedOnReadyStateChange","USE_NULL_FUNCTION","goog.net.XhrIo.prototype.cleanUpTimeoutTimer_","wd","goog.net.XhrIo.prototype.getReadyState","UNINITIALIZED","mc","goog.net.XhrIo.prototype.getResponse","TEXT","ARRAY_BUFFER","mozResponseArrayBuffer","exports.generateHttpHeadersOverwriteParam","Bd","Na","exports.setHttpHeadersWithOverwriteParam","Cd","urlParam","extraHeaders","httpHeaders","module$exports$goog$net$rpc$HttpCors.generateHttpHeadersOverwriteParam","getInternalChannelParam","paramName","defaultValue","internalChannelParams","goog.labs.net.webChannel.WebChannelBase","Ed","extraParams_","httpHeadersOverwriteParam_","initHeaders_","nextMapId_","nextRid_","failFast_","forwardChannelTimerId_","allowStreamingMode_","backChannelAttemptId_","forwardChannelRetryCount_","baseRetryDelayMs_","retryDelaySeedMs_","forwardChannelMaxRetries_","forwardChannelRequestTimeoutMs_","xmlHttpFactory","useFetchStreams","supportsCrossDomainXhr","concurrentRequestLimit","fastHandshake_","fastHandshake","encodeInitMessageHeaders_","encodeInitMessageHeaders","blockingHandshake_","blockingHandshake","detectBufferingProxy","longPollingTimeout_","longPollingTimeout","nonAckedMapsAtChannelClose_","bpDetectionTimerId_","Hc","WebChannelBase.prototype.disconnect","cancelRequests_","rid","addAdditionalParams_","requestSent","goog.globalnavigatorsendBeacon","sendBeacon","goog.globalImage","Image","onClose_","WebChannelBase.prototype.cancelBackChannelRequest_","zc","WebChannelBase.prototype.cancelRequests_","Fd","clearForwardChannelTimer_","WebChannelBase.prototype.ensureForwardChannel_","Gc","onStartForwardChannelTimer_","isFull","Ld","WebChannelBase.prototype.makeForwardChannelRequest_","opt_retryRequest","module$exports$goog$net$rpc$HttpCors.setHttpHeadersWithOverwriteParam","requeuePendingMaps_","requestText","dequeueOutgoingMaps_","goog.labs.net.webChannel.WebChannelBase.MAX_MAPS_PER_REQUEST_","WebChannelBase.prototype.addAdditionalParams_","Gd","WebChannelBase.prototype.dequeueOutgoingMaps_","Kd","maxNum","badMapHandler","badMapError","messageQueue","WireV8.prototype.encodeMessage","buffer","opt_prefix","encodedValue","encodeMessage","pendingMessages","WebChannelBase.prototype.ensureBackChannel_","Fc","onStartBackChannelTimer_","WebChannelBase.prototype.maybeRetryBackChannel_","goog.labs.net.webChannel.WebChannelBase.BACK_CHANNEL_MAX_RETRIES","getRetryTime_","vc","WebChannelBase.prototype.clearBpDetectionTimer_","WebChannelBase.prototype.startBackChannel_","Md","yc","WebChannelBase.prototype.clearDeadBackchannelTimer_","WebChannelBase.prototype.onRequestComplete","sc","WebChannelBase.prototype.maybeRetryForwardChannel_","BACK_CHANNEL","FORWARD_CHANNEL","lastError","maybeRetryForwardChannel_","INIT","getForwardChannelMaxRetries","maybeRetryBackChannel_","REQUEST_FAILED","WebChannelBase.prototype.getRetryTime_","Jd","retryTime","isActive","goog.labs.net.webChannel.WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR","WebChannelBase.prototype.signalError_","imageUri","testNetworkCallback_","goog.globallocation","goog.globallocationprotocol","netUtils.testLoadImage","goog.labs.net.webChannel.netUtils.imageCallback_","goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT","goog.labs.net.webChannel.netUtils.testLoadImage","ERROR_OTHER","onError_","channelError","Hd","WebChannelBase.prototype.onClose_","channelClosed","WebChannelBase.prototype.createDataUri","Dc","locationPage","hostName","opt_scheme","opt_domain","opt_port","getHttpSessionId","WebChannelBase.prototype.createXhrIo","lc","isStreaming","setWithCredentials","Nd","goog.labs.net.webChannel.WebChannelBaseTransport","Od","Q","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.base","messageUrlParams_","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","goog.net.WebChannel.X_CLIENT_PROTOCOL","goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL","initHeaders","initMessageHeaders","messageContentType","goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE","clientProfile","goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE","httpHeadersOverwriteParam","supportsCrossDomainXhr_","sendRawJson_","sendRawJson","httpSessionIdParam","channelHandler_","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.Handler_","Pd","goog.net.WebChannel.MessageEventcall","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.MessageEvent.base","__headers__","__status__","__sm__","metadataKey","Qd","goog.net.WebChannel.ErrorEventcall","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.ErrorEvent.base","NETWORK_ERROR","R","goog.crypt.Md5","S","block_","totalLength_","blockLength_","Sd","goog.crypt.Md5.prototype.compress_","opt_offset","X","sum","goog.math.Integer","sign","sign_","localBits","goog.net.XhrIo.prototype.setWithCredentials","withCredentials","JSC$2274_send","goog.net.XhrIo.prototype.send","opt_method","opt_content","opt_headers","createXhr","goog.net.XmlHttp.factory_createInstance","goog.net.XmlHttp.factory_getOptions","error_","content","getPrototypeOf","contentTypeKey","contentIsFormData","FormData","goog.net.XhrIo.CONTENT_TYPE_HEADER","goog.net.XhrIo.FORM_CONTENT_TYPE","z","goog.net.XhrIo.shouldUseXhr2Timeout_","goog.net.XhrIo.prototype","JSC$2274_timeout_","goog.net.XhrIo.prototype.timeout_","goog.net.XhrIo.prototype.abort","opt_failureCode","goog.net.XhrIo.prototype.disposeInternal","goog.net.XhrIo.prototype.disposeInternal.base","goog.net.XhrIo.prototype.onReadyStateChange_","isDisposed","onReadyStateChangeHelper_","onReadyStateChangeEntryPoint_","goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_","goog.net.XhrIo.prototype.isActive","goog.net.XhrIo.prototype.getStatus","goog.net.XhrIo.prototype.getResponseText","getResponseJson","goog.net.XhrIo.prototype.getResponseJson","opt_xssiPrefix","rd","goog.net.XhrIo.prototype.getLastErrorCode","JSC$2274_getLastError","goog.net.XhrIo.prototype.getLastError","goog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION","JSC$2281_state_","goog.labs.net.webChannel.WebChannelBase.prototype","WebChannelBase.prototype.onStartForwardChannelTimer_","startForwardChannel_","total","goog.labs.net.webChannel.Wire.RAW_DATA_KEY","__data__","goog.labs.net.webChannel.WebChannelBase.MAX_CHARS_PER_GET_","goog.net.WebChannelTransport.CLIENT_VERSION","xmlHttpPost","makeForwardChannelRequest_","WebChannelBase.prototype.onStartBackChannelTimer_","bpDetectionTimeout","startBackChannel_","onBpDetectionTimer_","WebChannelBase.prototype.onBpDetectionTimer_","PROXY","WebChannelBase.prototype.onBackChannelDead_","BACKCHANNEL_DEAD","WebChannelBase.prototype.testNetworkCallback_","networkUp","ERROR_NETWORK","WebChannelBase.prototype.isActive","WebChannelBase.Handler.prototype.channelOpened","WebChannelBase.Handler.prototype.channelHandleArray","goog.labs.net.webChannel.WebChannelBase.Handler.prototype","WebChannelBase.Handler.prototype.channelError","WebChannelBase.Handler.prototype.channelClosed","WebChannelBase.Handler.prototype.isActive","WebChannelBase.Handler.prototype.badMapError","createWebChannel","WebChannelBaseTransport.prototype.createWebChannel","goog.labs.net.webChannel.WebChannelBaseTransport.Channel","WebChannelBaseTransport.Channel.prototype.open","supportCrossDomain","CONNECT_ATTEMPT","channelPath","opt_extraParams","connectChannel_","WebChannelBaseTransport.Channel.prototype.close","WebChannelBaseTransport.Channel.prototype.send","rawJson","messageToMapObject_","WebChannelBaseTransport.Channel.prototype.disposeInternal","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.disposeInternal.base","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.crypt.Hash","goog.crypt.Md5.prototype.reset","goog.crypt.Md5.prototype.update","opt_length","block","blockLength","goog.crypt.Md5.prototype.digest","goog.math.Integer.IntCache_","goog.math.Integer.fromInt","Td","valueFn","cacheObj","goog.reflect.cache","goog.math.Integer.fromNumber","U","isFinite","V","goog.math.Integer.TWO_PWR_32_DBL_","goog.math.Integer.ZERO","goog.math.Integer.ONE","goog.math.Integer.TWO_PWR_24_","goog.math.Integer.prototype.isZero","Y","goog.math.Integer.prototype.isNegative","goog.math.Integer.prototype.negate","not","Zd","goog.math.Integer.prototype.subtract","negate","$d","goog.math.Integer.DivisionResult","ae","quotient","remainder","goog.math.Integer.prototype.divideAndRemainder","Yd","isZero","isNegative","divideAndRemainder","slowDivide_","twoPower","multiple","shiftLeft","shiftRight","total2","subtract","multiply","rem","approxRem","approx","toNumber","log2","ceil","approxRes","goog.math.Integer.prototype.shiftLeft","getBits","bit_delta","goog.math.Integer.prototype.shiftRight","Z","numBits","arr_delta","T","goog.math.Integer.prototype.toNumber","getBitsUnsigned","goog.math.Integer.prototype.toString","opt_radix","radix","radixToPower","remDiv","toInt","goog.math.Integer.prototype","goog.math.Integer.prototype.getBits","JSC$2306_compare","goog.math.Integer.prototype.compare","diff","goog.math.Integer.prototype.abs","goog.math.Integer.prototype.add","carry","c0","JSC$2306_multiply","goog.math.Integer.prototype.multiply","lessThan","a1","a0","b1","b0","goog.math.Integer.carry16_","modulo","goog.math.Integer.prototype.modulo","and","goog.math.Integer.prototype.and","or","goog.math.Integer.prototype.or","xor","goog.math.Integer.prototype.xor","Sb","EventType","Xb","getLastError","fromNumber","fromString","goog.math.Integer.fromString","Vd","power","__PRIVATE_RpcCode","getStatEventTarget","ErrorCode","Event","Stat","module","XhrIo","Md5","Integer","isAuthenticated","toKey","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","__PRIVATE_logClient","__PRIVATE_getLogLevel","__PRIVATE_logDebug","__PRIVATE_argToString","__PRIVATE_logError","__PRIVATE_logWarn","fail","__PRIVATE_failure","__PRIVATE_hardAssert","Code","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","UNAVAILABLE","DATA_LOSS","FirestoreError","__PRIVATE_Deferred","__PRIVATE_OAuthToken","__PRIVATE_EmptyAuthCredentialsProvider","invalidateToken","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","__PRIVATE_FirebaseAuthCredentialsProvider","__PRIVATE_authProvider","__PRIVATE_tokenCounter","__PRIVATE_lastTokenId","__PRIVATE_guardedChangeListener","__PRIVATE_nextToken","__PRIVATE_tokenListener","__PRIVATE_getUser","__PRIVATE_awaitNextToken","__PRIVATE_currentTokenAttempt","__PRIVATE_registerAuth","__PRIVATE_initialTokenCounter","__PRIVATE_tokenData","__PRIVATE_currentUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE__headers","__PRIVATE_getAuthToken","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","__PRIVATE_FirebaseAppCheckTokenProvider","__PRIVATE_appCheckProvider","__PRIVATE_latestAppCheckToken","tokenResult","__PRIVATE_tokenUpdated","__PRIVATE_registerAppCheck","__PRIVATE_AutoId","static","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","__PRIVATE_nBytes","__PRIVATE_i","__PRIVATE_randomBytes","__PRIVATE_primitiveComparator","__PRIVATE_arrayEquals","__PRIVATE_immediateSuccessor","Timestamp","nanoseconds","fromMillis","milliseconds","nanos","toDate","toMillis","_compareTo","__PRIVATE_adjustedSeconds","SnapshotVersion","toMicroseconds","toTimestamp","BasePath","segments","nameOrPath","construct","popFirst","popLast","firstSegment","lastSegment","isPrefixOf","isImmediateParentOf","potentialChild","end","p1","p2","ResourcePath","canonicalString","toUriEncodedString","pathComponents","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","isKeyField","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","DocumentKey","emptyPath","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","FieldIndex","indexId","fields","indexState","__PRIVATE_fieldIndexGetArraySegment","__PRIVATE_fieldIndex","__PRIVATE_fieldIndexGetDirectionalSegments","UNKNOWN_ID","IndexSegment","fieldPath","IndexState","sequenceNumber","IndexOffset","__PRIVATE_newIndexOffsetSuccessorFromReadTime","readTime","largestBatchId","__PRIVATE_successorSeconds","__PRIVATE_successorNanos","__PRIVATE_successor","fromTimestamp","__PRIVATE_newIndexOffsetFromDocument","documentKey","__PRIVATE_indexOffsetComparator","__PRIVATE_PRIMARY_LEASE_LOST_ERROR_MSG","PersistenceTransaction","onCommittedListeners","addOnCommittedListener","raiseOnCommittedEvent","__PRIVATE_ignoreIfPrimaryLeaseLoss","PersistencePromise","nextCallback","catchCallback","isDone","callbackAttached","catchFn","wrapFailure","wrapSuccess","wrapUserFunction","expectedCount","__PRIVATE_resolvedCount","element","predicates","__PRIVATE_isTrue","__PRIVATE_promises","waitFor","condition","__PRIVATE_SimpleDbTransaction","aborted","__PRIVATE_completionDeferred","oncomplete","__PRIVATE_IndexedDbTransactionError","__PRIVATE_checkForAndReportiOSError","__PRIVATE_completionPromise","__PRIVATE_maybeCommit","__PRIVATE_maybeV3IndexedDb","commit","__PRIVATE_storeName","__PRIVATE_SimpleDbStore","__PRIVATE_SimpleDb","__PRIVATE_schemaConverter","__PRIVATE_getIOSVersion","__PRIVATE_wrapRequest","__PRIVATE_isMockPersistence","__PRIVATE_ua","__PRIVATE_iOSVersion","__PRIVATE_isUnsupportedIOS","__PRIVATE_androidVersion","__PRIVATE_getAndroidVersion","__PRIVATE_isUnsupportedAndroid","__PRIVATE_env","__PRIVATE_USE_MOCK_PERSISTENCE","__PRIVATE_iOSVersionRegex","__PRIVATE_androidVersionRegex","onblocked","__PRIVATE_createOrUpgrade","__PRIVATE_versionchangelistener","onversionchange","__PRIVATE_setVersionChangeListener","__PRIVATE_versionChangeListener","__PRIVATE_objectStores","__PRIVATE_transactionFn","__PRIVATE_readonly","__PRIVATE_attemptNumber","__PRIVATE_ensureDb","__PRIVATE_transactionFnResult","__PRIVATE_retryable","__PRIVATE_IterationController","__PRIVATE_dbCursor","__PRIVATE_shouldStop","__PRIVATE_nextKey","__PRIVATE_skipToKey","cursor","__PRIVATE_skip","__PRIVATE_actionName","cause","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_keyOrValue","__PRIVATE_loadAll","__PRIVATE_indexOrRange","range","__PRIVATE_iterateOptions","__PRIVATE_iterateCursor","__PRIVATE_loadFirst","__PRIVATE_deleteAll","__PRIVATE_keysOnly","control","__PRIVATE_iterate","__PRIVATE_optionsOrCallback","__PRIVATE_iterateSerial","__PRIVATE_cursorRequest","primaryKey","__PRIVATE_shouldContinue","__PRIVATE_userResult","__PRIVATE_userPromise","__PRIVATE_indexName","direction","openKeyCursor","openCursor","__PRIVATE_reportedIOSError","__PRIVATE_IOS_ERROR","__PRIVATE_newError","__PRIVATE_IndexBackfillerScheduler","__PRIVATE_backfiller","__PRIVATE_schedule","started","delay","enqueueAfterDelay","__PRIVATE_backfill","__PRIVATE_IndexBackfiller","localStore","__PRIVATE_maxDocumentsToProcess","__PRIVATE_writeIndexEntries","__PRIVATE_transation","__PRIVATE_processedCollectionGroups","__PRIVATE_documentsRemaining","__PRIVATE_continueLoop","doWhile","indexManager","getNextCollectionGroupToUpdate","__PRIVATE_writeEntriesForCollectionGroup","__PRIVATE_documentsProcessed","__PRIVATE_documentsRemainingUnderCap","getMinOffsetFromCollectionGroup","__PRIVATE_existingOffset","localDocuments","getNextDocuments","__PRIVATE_nextBatch","docs","updateIndexEntries","__PRIVATE_getNewOffset","__PRIVATE_newOffset","updateCollectionGroup","__PRIVATE_lookupResult","__PRIVATE_maxOffset","batchId","__PRIVATE_ListenSequence","previousValue","__PRIVATE_sequenceNumberSyncer","sequenceNumberHandler","__PRIVATE_setPreviousValue","__PRIVATE_writeNewSequenceNumber","writeSequenceNumber","__PRIVATE_externalPreviousValue","__PRIVATE_nextValue","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_encodeResourcePath","__PRIVATE_encodeSeparator","__PRIVATE_resultBuf","__PRIVATE_escapeChar","__PRIVATE_encodeSegment","__PRIVATE_decodeResourcePath","__PRIVATE_lastReasonableEscapeIndex","__PRIVATE_segmentBuilder","__PRIVATE_currentPiece","__PRIVATE_INVALID","__PRIVATE_DbMutationBatchUserMutationsKeyPath","__PRIVATE_newDbDocumentMutationPrefixForPath","userId","__PRIVATE_newDbDocumentMutationKey","__PRIVATE_DbDocumentMutationPlaceholder","__PRIVATE_DbRemoteDocumentKeyPath","__PRIVATE_DbRemoteDocumentDocumentKeyIndexPath","__PRIVATE_DbRemoteDocumentCollectionGroupIndexPath","__PRIVATE_DbTargetQueryTargetsKeyPath","__PRIVATE_DbTargetDocumentKeyPath","__PRIVATE_DbTargetDocumentDocumentTargetsKeyPath","__PRIVATE_DbCollectionParentKeyPath","__PRIVATE_DbIndexStateKeyPath","__PRIVATE_DbIndexStateSequenceNumberIndexPath","__PRIVATE_DbIndexEntryKeyPath","__PRIVATE_DbIndexEntryDocumentKeyIndexPath","__PRIVATE_DbDocumentOverlayKeyPath","__PRIVATE_DbDocumentOverlayCollectionPathOverlayIndexPath","__PRIVATE_DbDocumentOverlayCollectionGroupOverlayIndexPath","__PRIVATE_V11_STORES","__PRIVATE_V12_STORES","__PRIVATE_V13_STORES","__PRIVATE_V14_STORES","__PRIVATE_V15_STORES","__PRIVATE_IndexedDbTransaction","__PRIVATE_simpleDbTransaction","currentSequenceNumber","__PRIVATE_getStore","__PRIVATE_indexedDbTransaction","__PRIVATE_objectSize","EMPTY","__PRIVATE_prunedNodes","__PRIVATE_descriptions","isReverse","nodeStack","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","SortedSet","elem","first","forEachInRange","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","__PRIVATE_advanceIterator","__PRIVATE_it","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","__PRIVATE_Base64DecodeError","ByteString","binaryString","__PRIVATE_encoded","Symbol","toBase64","toUint8Array","approximateByteSize","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","__PRIVATE_normalizeTimestamp","__PRIVATE_normalizeNumber","__PRIVATE_fraction","__PRIVATE_nanoStr","__PRIVATE_parsedDate","__PRIVATE_normalizeByteString","fromBase64String","fromUint8Array","__PRIVATE_isServerTimestamp","mapValue","__type__","stringValue","__PRIVATE_getPreviousValue","__previous_value__","__PRIVATE_getLocalWriteTime","localWriteTime","__local_write_time__","timestampValue","DatabaseInfo","databaseId","ssl","autoDetectLongPolling","longPollingOptions","DatabaseId","isDefaultDatabase","MAX_VALUE","MIN_VALUE","nullValue","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","bytesValue","referenceValue","geoPointValue","latitude","longitude","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","arrayValue","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","__PRIVATE_valueCompare","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_rightType","__PRIVATE_compareTimestamps","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","comparison","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_leftKeys","__PRIVATE_rightKeys","__PRIVATE_keyCompare","canonicalId","__PRIVATE_canonifyValue","__PRIVATE_normalizedTimestamp","byteString","fromName","__PRIVATE_geoPoint","__PRIVATE_sortedKeys","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","__PRIVATE_lowerBoundCompare","inclusive","__PRIVATE_upperBoundCompare","ObjectValue","field","__PRIVATE_currentLevel","getFieldsMap","setAll","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","createTime","documentState","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","Bound","__PRIVATE_boundCompareToDocument","bound","__PRIVATE_orderByComponent","dir","__PRIVATE_boundEquals","OrderBy","Filter","FieldFilter","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matchesComparison","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","__PRIVATE_subfilter","compositeFilter","__PRIVATE_compositeFilterIsDisjunction","__PRIVATE_compositeFilterIsFlatConjunction","__PRIVATE_compositeFilterIsFlat","__PRIVATE_compositeFilterWithAddedFilters","__PRIVATE_otherFilters","__PRIVATE_mergedFilters","__PRIVATE_stringifyFilter","__PRIVATE_extractDocumentKeysFromArrayValue","__PRIVATE_TargetImpl","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_canonifyTarget","__PRIVATE_targetImpl","__PRIVATE_canonifyFilter","__PRIVATE_canonicalIdsString","__PRIVATE_targetEquals","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_f1Filter","__PRIVATE_targetIsDocumentTarget","isDocumentKey","__PRIVATE_targetGetFieldFiltersForPath","__PRIVATE_targetGetAscendingBound","fieldFilter","__PRIVATE_filterValue","__PRIVATE_filterInclusive","NaN","__PRIVATE_cursorValue","__PRIVATE_targetGetDescendingBound","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_newQuery","__PRIVATE_newQueryForPath","__PRIVATE_queryMatchesAllDocuments","__PRIVATE_isCollectionGroupQuery","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","keyField","__PRIVATE_queryToTarget","__PRIVATE_orderBys","__PRIVATE__queryToTarget","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryWithLimit","__PRIVATE_queryEquals","__PRIVATE_canonifyQuery","__PRIVATE_stringifyQuery","__PRIVATE_queryMatches","__PRIVATE_docPath","__PRIVATE_queryCollectionGroup","__PRIVATE_newQueryComparator","__PRIVATE_d1","__PRIVATE_d2","__PRIVATE_comparedOnKeyField","comp","__PRIVATE_compareDocs","v1","v2","ObjectMap","mapKeyFn","equalsFn","innerSize","__PRIVATE_otherKey","__PRIVATE_EMPTY_MUTABLE_DOCUMENT_MAP","__PRIVATE_EMPTY_DOCUMENT_MAP","documentMap","__PRIVATE_convertOverlayedDocumentMapToDocumentMap","documents","overlayedDocument","__PRIVATE_newDocumentKeyMap","__PRIVATE_EMPTY_DOCUMENT_VERSION_MAP","__PRIVATE_EMPTY_DOCUMENT_KEY_SET","__PRIVATE_documentKeySet","__PRIVATE_EMPTY_TARGET_ID_SET","__PRIVATE_toDouble","serializer","useProto3Json","__PRIVATE_toInteger","TransformOperation","__PRIVATE_computeTransformOperationBaseValue","transform","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_applyArrayUnionTransformOperation","__PRIVATE_coercedFieldValuesArray","__PRIVATE_toUnion","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_applyArrayRemoveTransformOperation","__PRIVATE_toRemove","__PRIVATE_operand","asNumber","FieldTransform","MutationResult","transformResults","Precondition","updateTime","isNone","__PRIVATE_preconditionIsValidForDocument","precondition","Mutation","__PRIVATE_calculateOverlayMutation","__PRIVATE_DeleteMutation","none","__PRIVATE_SetMutation","__PRIVATE_docValue","__PRIVATE_patchValue","__PRIVATE_maskSet","__PRIVATE_PatchMutation","__PRIVATE_mutationApplyToRemoteDocument","mutation","__PRIVATE_mutationResult","__PRIVATE_newData","__PRIVATE_serverTransformResults","fieldTransforms","__PRIVATE_getPatch","__PRIVATE_mutationApplyToLocalView","__PRIVATE_previousMask","__PRIVATE_localTransformResults","fieldMask","__PRIVATE_mutationEquals","__PRIVATE_fieldTransformEquals","getFieldMask","__PRIVATE_mutableDocument","__PRIVATE_fieldTransform","__PRIVATE_transformResult","__PRIVATE_applyTransformOperationToRemoteDocument","__PRIVATE_baseValue","__PRIVATE_applyTransformOperationToLocalView","__PRIVATE_VerifyMutation","MutationBatch","baseMutations","mutations","applyToRemoteDocument","batchResult","mutationResults","applyToLocalView","mutatedFields","applyToLocalDocumentSet","documentsWithoutRemoteVersion","overlays","__PRIVATE_overlay","MutationBatchResult","batch","commitVersion","docVersions","__PRIVATE_versionMap","Overlay","ExistenceFilter","unchangedNames","__PRIVATE_isPermanentError","__PRIVATE_mapCodeFromRpcCode","__PRIVATE_newTextEncoder","RpcCode","__PRIVATE_MAX_64_BIT_UNSIGNED_INTEGER","__PRIVATE_getMd5HashValue","__PRIVATE_encodedValue","__PRIVATE_md5","__PRIVATE_get64BitUints","Bytes","__PRIVATE_dataView","DataView","__PRIVATE_chunk1","getUint32","__PRIVATE_chunk2","__PRIVATE_chunk3","__PRIVATE_chunk4","BloomFilter","bitmap","padding","hashCount","__PRIVATE_BloomFilterError","__PRIVATE_bitCount","__PRIVATE_bitCountInInteger","__PRIVATE_getBitIndex","__PRIVATE_num1","__PRIVATE_num2","__PRIVATE_hashIndex","__PRIVATE_hashValue","__PRIVATE_isBitSet","mightContain","__PRIVATE_md5HashedValue","__PRIVATE_hash1","__PRIVATE_hash2","bloomFilter","__PRIVATE_setBit","__PRIVATE_indexOfByte","RemoteEvent","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","resumeToken","TargetChange","createSynthesizedTargetChangeForCurrentChange","addedDocuments","modifiedDocuments","removedDocuments","__PRIVATE_DocumentWatchChange","__PRIVATE_updatedTargetIds","removedTargetIds","__PRIVATE_newDoc","__PRIVATE_ExistenceFilterChange","__PRIVATE_existenceFilter","__PRIVATE_WatchTargetChange","targetIds","__PRIVATE_TargetState","__PRIVATE_pendingResponses","__PRIVATE_documentChanges","__PRIVATE_snapshotChangesMap","__PRIVATE__resumeToken","__PRIVATE__current","__PRIVATE__hasPendingChanges","__PRIVATE_isPending","__PRIVATE_hasPendingChanges","__PRIVATE_updateResumeToken","__PRIVATE_toTargetChange","changeType","__PRIVATE_clearPendingChanges","__PRIVATE_addDocumentChange","__PRIVATE_removeDocumentChange","__PRIVATE_recordPendingTargetRequest","__PRIVATE_recordTargetResponse","__PRIVATE_markCurrent","__PRIVATE_WatchChangeAggregator","__PRIVATE_metadataProvider","__PRIVATE_targetStates","__PRIVATE_pendingDocumentUpdates","__PRIVATE_pendingDocumentTargetMapping","__PRIVATE_documentTargetMap","__PRIVATE_pendingTargetResets","__PRIVATE_handleDocumentChange","__PRIVATE_docChange","__PRIVATE_addDocumentToTarget","__PRIVATE_removeDocumentFromTarget","__PRIVATE_handleTargetChange","targetChange","forEachTarget","__PRIVATE_targetState","__PRIVATE_ensureTargetState","__PRIVATE_isActiveTarget","removeTarget","__PRIVATE_resetTarget","__PRIVATE_handleExistenceFilter","__PRIVATE_watchChange","targetData","__PRIVATE_targetDataForActiveTarget","newNoDocument","__PRIVATE_currentSize","__PRIVATE_getCurrentDocumentCountForTarget","__PRIVATE_parseBloomFilter","__PRIVATE_applyBloomFilter","purpose","__PRIVATE_normalizedBitmap","__PRIVATE_currentCount","__PRIVATE_filterRemovedDocuments","__PRIVATE_existingKeys","getRemoteKeysForTarget","__PRIVATE_removalCount","__PRIVATE_getDatabaseId","documentPath","__PRIVATE_createRemoteEvent","__PRIVATE_targetContainsDocument","__PRIVATE_targets","__PRIVATE_isOnlyLimboTarget","remoteEvent","__PRIVATE_ensureDocumentTargetMapping","__PRIVATE_updatedDocument","__PRIVATE_targetMapping","__PRIVATE_targetActive","__PRIVATE_getTargetDataForTarget","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","__PRIVATE_toInt32Proto","__PRIVATE_toBytes","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fromResourceName","__PRIVATE_resource","__PRIVATE_isValidResourceName","__PRIVATE_toName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_toQueryPath","__PRIVATE_fromQueryPath","__PRIVATE_resourceName","__PRIVATE_getEncodedDatabaseId","__PRIVATE_toMutationDocument","__PRIVATE_fromDocument","newFoundDocument","toMutation","updateMask","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_toDocumentMask","updateTransforms","setToServerValue","appendMissingElements","removeAllFromArray","currentDocument","__PRIVATE_fromMutation","proto","fromServerFormat","paths","__PRIVATE_toDocumentsTarget","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","allDescendants","__PRIVATE_toFilter","unaryFilter","__PRIVATE_toFieldPathReference","__PRIVATE_toOperatorName","__PRIVATE_protos","__PRIVATE_toCompositeOperatorName","before","__PRIVATE_convertQueryTargetToQuery","__PRIVATE_fromCount","__PRIVATE_filterBy","__PRIVATE_fromFilter","__PRIVATE_nanField","__PRIVATE_fromFieldPathReference","__PRIVATE_nullField","__PRIVATE_notNanField","__PRIVATE_notNullField","__PRIVATE_fieldReference","TargetData","lastLimboFreeSnapshotVersion","withSequenceNumber","withResumeToken","withExpectedCount","withLastLimboFreeSnapshotVersion","__PRIVATE_LocalSerializer","__PRIVATE_remoteSerializer","__PRIVATE_toDbRemoteDocument","__PRIVATE_localSerializer","__PRIVATE_remoteDoc","documentId","__PRIVATE_toDbTimestampKey","noDocument","__PRIVATE_toDbTimestamp","unknownDocument","__PRIVATE_fromDbTimestamp","__PRIVATE_dbTimestamp","__PRIVATE_fromDbMutationBatch","__PRIVATE_dbBatch","__PRIVATE_currentMutation","__PRIVATE_transformMutation","localWriteTimeMs","__PRIVATE_fromDbTarget","__PRIVATE_dbTarget","__PRIVATE_documentsTarget","lastListenSequenceNumber","__PRIVATE_toDbTarget","__PRIVATE_dbLastLimboFreeTimestamp","__PRIVATE_queryProto","__PRIVATE_fromBundledQuery","bundledQuery","__PRIVATE_fromDbDocumentOverlay","__PRIVATE_dbDocumentOverlay","overlayMutation","__PRIVATE_toDbDocumentOverlayKey","__PRIVATE_docKey","__PRIVATE_docId","__PRIVATE_toDbIndexState","__PRIVATE_IndexedDbBundleCache","getBundleMetadata","__PRIVATE_bundlesStore","__PRIVATE_bundle","__PRIVATE_dbBundle","saveBundleMetadata","__PRIVATE_bundleMetadata","getNamedQuery","queryName","__PRIVATE_namedQueriesStore","__PRIVATE_dbNamedQuery","saveNamedQuery","__PRIVATE_IndexedDbDocumentOverlayCache","getOverlay","__PRIVATE_documentOverlayStore","__PRIVATE_dbOverlay","getOverlays","saveOverlays","__PRIVATE_saveOverlay","removeOverlaysForBatchId","documentKeys","__PRIVATE_collectionPaths","collectionPath","IDBKeyRange","getOverlaysForCollection","sinceBatchId","__PRIVATE_dbOverlays","getOverlaysForCollectionGroup","__PRIVATE_currentBatchId","__PRIVATE_toDbDocumentOverlay","__PRIVATE_FirestoreIndexValueWriter","__PRIVATE_writeIndexValue","__PRIVATE_encoder","__PRIVATE_writeIndexValueAux","__PRIVATE_writeInfinity","__PRIVATE_indexValue","__PRIVATE_writeValueTypeLabel","__PRIVATE_writeNumber","__PRIVATE_writeString","__PRIVATE_writeIndexString","__PRIVATE_writeTruncationMarker","__PRIVATE_writeBytes","__PRIVATE_writeIndexEntityRef","__PRIVATE_writeIndexMap","__PRIVATE_writeIndexArray","__PRIVATE_stringIndexValue","__PRIVATE_writeUnlabeledIndexString","__PRIVATE_mapIndexValue","__PRIVATE_arrayIndexValue","__PRIVATE_unsignedNumLength","__PRIVATE_numBits","__PRIVATE_leadingZeros","__PRIVATE_zeros","__PRIVATE_numberOfLeadingZerosInByte","__PRIVATE_INSTANCE","__PRIVATE_OrderedCodeWriter","__PRIVATE_writeBytesAscending","__PRIVATE_byte","__PRIVATE_writeByteAscending","__PRIVATE_writeSeparatorAscending","__PRIVATE_writeBytesDescending","__PRIVATE_writeByteDescending","__PRIVATE_writeSeparatorDescending","__PRIVATE_writeUtf8Ascending","__PRIVATE_sequence","charCode","__PRIVATE_codePoint","codePointAt","__PRIVATE_writeUtf8Descending","__PRIVATE_writeNumberAscending","__PRIVATE_toOrderedBits","__PRIVATE_ensureAvailable","__PRIVATE_writeNumberDescending","__PRIVATE_writeInfinityAscending","__PRIVATE_writeEscapedByteAscending","__PRIVATE_writeInfinityDescending","__PRIVATE_writeEscapedByteDescending","seed","__PRIVATE_encodedBytes","__PRIVATE_dv","setFloat64","__PRIVATE_isNegative","__PRIVATE_masked","__PRIVATE_minCapacity","__PRIVATE_newLength","__PRIVATE_newBuffer","__PRIVATE_AscendingIndexByteEncoder","__PRIVATE_orderedCode","__PRIVATE_DescendingIndexByteEncoder","__PRIVATE_IndexByteEncoder","__PRIVATE_ascending","__PRIVATE_descending","__PRIVATE_forKind","__PRIVATE_IndexEntry","directionalValue","__PRIVATE_currentLength","__PRIVATE_indexEntryComparator","__PRIVATE_compareByteArrays","__PRIVATE_TargetIndexMatcher","__PRIVATE_inequalityFilters","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_equalityFilters","__PRIVATE_hasMultipleInequality","__PRIVATE_servedByIndex","__PRIVATE_arraySegment","__PRIVATE_hasMatchingEqualityFilter","__PRIVATE_equalitySegments","__PRIVATE_segmentIndex","__PRIVATE_orderBysIndex","__PRIVATE_inequalityFilter","__PRIVATE_matchesFilter","__PRIVATE_matchesOrderBy","__PRIVATE_buildTargetIndex","__PRIVATE_uniqueFields","__PRIVATE_isArrayOperator","__PRIVATE_getDnfTerms","__PRIVATE_computeDistributedNormalForm","__PRIVATE_newFilter","__PRIVATE_applyAssociation","__PRIVATE_isDisjunctiveNormalForm","__PRIVATE_runningResult","__PRIVATE_applyDistribution","__PRIVATE_computeInExpansion","__PRIVATE_expandedFilters","__PRIVATE_isSingleFieldFilter","__PRIVATE_isFlatConjunction","__PRIVATE_subFilter","__PRIVATE_applyDistributionFieldAndCompositeFilters","__PRIVATE_disjunctionSide","__PRIVATE_otherSide","__PRIVATE_updatedFilters","__PRIVATE_newSubfilters","__PRIVATE_MemoryIndexManager","__PRIVATE_collectionParentIndex","__PRIVATE_MemoryCollectionParentIndex","addToCollectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","deleteAllFieldIndexes","createTargetIndexes","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getMinOffset","__PRIVATE_existingParents","__PRIVATE_added","__PRIVATE_EMPTY_VALUE","__PRIVATE_IndexedDbIndexManager","__PRIVATE_collectionParentsCache","__PRIVATE_targetToDnfSubTargets","__PRIVATE_collectionParent","__PRIVATE_collectionParentsStore","__PRIVATE_parentPaths","indexes","__PRIVATE_indexConfigurationStore","__PRIVATE_dbIndex","__PRIVATE_states","__PRIVATE_indexStateStore","__PRIVATE_indexEntriesStore","__PRIVATE_getSubTargets","__PRIVATE_subTarget","__PRIVATE_indexEntries","__PRIVATE_canServeTarget","__PRIVATE_getFieldIndex","__PRIVATE_arrayValues","__PRIVATE_notInValues","__PRIVATE_segmentBound","__PRIVATE_lowerBoundEncoded","__PRIVATE_encodeBound","__PRIVATE_upperBoundEncoded","__PRIVATE_notInEncoded","__PRIVATE_encodeValues","__PRIVATE_indexRanges","__PRIVATE_generateIndexRanges","__PRIVATE_indexRange","fromSegments","__PRIVATE_subTargets","__PRIVATE_term","__PRIVATE_lowerBounds","__PRIVATE_lowerBoundInclusive","__PRIVATE_upperBounds","__PRIVATE_upperBoundInclusive","__PRIVATE_totalScans","__PRIVATE_scansPerArrayElement","__PRIVATE_encodeSingleElement","__PRIVATE_generateLowerBound","__PRIVATE_generateUpperBound","__PRIVATE_notInBound","__PRIVATE_notIn","createRange","__PRIVATE_targetIndexMatcher","candidate","__PRIVATE_indexType","__PRIVATE_hasArraySegment","__PRIVATE_encodeDirectionalElements","__PRIVATE_directionalEncoder","__PRIVATE_encodeDirectionalKey","__PRIVATE_directionalSegments","__PRIVATE_encoders","__PRIVATE_valueIdx","__PRIVATE_isInFilter","__PRIVATE_expandIndexValues","__PRIVATE_getEncodedBytes","prefixes","__PRIVATE_arrayElement","__PRIVATE_clonedEncoder","__PRIVATE_indexConfigs","__PRIVATE_indexConfig","__PRIVATE_decodedState","__PRIVATE_decodedSegments","__PRIVATE_getNextSequenceNumber","__PRIVATE_nextSequenceNumber","__PRIVATE_configs","__PRIVATE_memoizedIndexes","__PRIVATE_memoizedCollectionIndexes","__PRIVATE_fieldIndexes","__PRIVATE_getExistingIndexEntries","__PRIVATE_existingEntries","__PRIVATE_newEntries","__PRIVATE_computeIndexEntries","__PRIVATE_updateEntries","__PRIVATE_addIndexEntry","__PRIVATE_indexEntry","orderedDocumentKey","__PRIVATE_deleteIndexEntry","only","after","__PRIVATE_onAdd","__PRIVATE_onRemove","__PRIVATE_beforeIt","__PRIVATE_afterIt","__PRIVATE_beforeValue","__PRIVATE_afterValue","__PRIVATE_removed","lower","upper","__PRIVATE_bounds","__PRIVATE_notInValue","__PRIVATE_cmpToLower","__PRIVATE_cmpToUpper","__PRIVATE_ranges","__PRIVATE_isRangeMatchable","__PRIVATE_getMinOffsetFromFieldIndexes","mapArray","__PRIVATE_minOffset","__PRIVATE_maxBatchId","__PRIVATE_GC_DID_NOT_RUN","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","LruParams","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","cacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","removeMutationBatch","__PRIVATE_mutationStore","__PRIVATE_indexTxn","__PRIVATE_numDeleted","__PRIVATE_removePromise","__PRIVATE_indexKey","__PRIVATE_dbDocumentSize","DISABLED","__PRIVATE_IndexedDbMutationQueue","referenceDelegate","__PRIVATE_documentKeysByBatchId","checkEmpty","__PRIVATE_mutationsStore","addMutationBatch","__PRIVATE_documentStore","__PRIVATE_documentMutationsStore","__PRIVATE_serializedBaseMutations","__PRIVATE_serializedMutations","__PRIVATE_collectionParents","lookupMutationBatch","__PRIVATE_lookupMutationKeys","getNextMutationBatchAfterBatchId","__PRIVATE_nextBatchId","__PRIVATE_foundBatch","getHighestUnacknowledgedBatchId","getAllMutationBatches","__PRIVATE_dbBatches","getAllMutationBatchesAffectingDocumentKey","__PRIVATE_indexPrefix","__PRIVATE_indexStart","__PRIVATE_userID","__PRIVATE_encodedPath","getAllMutationBatchesAffectingDocumentKeys","__PRIVATE_uniqueBatchIDs","__PRIVATE_batchID","__PRIVATE_lookupMutationBatches","getAllMutationBatchesAffectingQuery","__PRIVATE_queryPath","__PRIVATE_immediateChildrenLength","__PRIVATE_batchIDs","__PRIVATE_removeCachedMutationKeys","markPotentiallyOrphaned","performConsistencyCheck","__PRIVATE_startRange","__PRIVATE_danglingMutationReferences","__PRIVATE_mutationQueueContainsKey","__PRIVATE_getMutationQueueMetadata","__PRIVATE_mutationQueuesStore","lastAcknowledgedBatchId","lastStreamToken","__PRIVATE_TargetIdGenerator","__PRIVATE_lastId","__PRIVATE_IndexedDbTargetCache","allocateTargetId","__PRIVATE_retrieveMetadata","__PRIVATE_targetIdGenerator","highestTargetId","__PRIVATE_saveMetadata","getLastRemoteSnapshotVersion","lastRemoteSnapshotVersion","getHighestSequenceNumber","__PRIVATE_targetGlobal","highestListenSequenceNumber","setTargetsMetadata","addTargetData","__PRIVATE_saveTargetData","targetCount","__PRIVATE_updateMetadataFromTargetData","updateTargetData","removeTargetData","removeMatchingKeysForTargetId","__PRIVATE_targetsStore","removeTargets","activeTargetIds","__PRIVATE_globalTargetStore","updated","getTargetCount","getTargetData","found","addMatchingKeys","__PRIVATE_documentTargetStore","addReference","removeMatchingKeys","removeReference","getMatchingKeysForTargetId","__PRIVATE_bufferEntryComparator","__PRIVATE_aSequence","__PRIVATE_aIndex","__PRIVATE_bSequence","__PRIVATE_bIndex","__PRIVATE_seqCmp","__PRIVATE_RollingSequenceNumberBuffer","__PRIVATE_maxElements","__PRIVATE_previousIndex","__PRIVATE_nextIndex","__PRIVATE_addElement","__PRIVATE_highestValue","maxValue","__PRIVATE_LruScheduler","garbageCollector","__PRIVATE_gcTask","__PRIVATE_scheduleGC","collectGarbage","__PRIVATE_LruGarbageCollectorImpl","__PRIVATE_delegate","calculateTargetCount","percentile","__PRIVATE_getSequenceNumberCount","nthSequenceNumber","__PRIVATE_forEachOrphanedDocumentSequenceNumber","removeOrphanedDocuments","collect","getCacheSize","__PRIVATE_runGarbageCollection","__PRIVATE_upperBoundSequenceNumber","__PRIVATE_sequenceNumbersToCollect","__PRIVATE_countedTargetsTs","__PRIVATE_foundUpperBoundTs","__PRIVATE_removedTargetsTs","__PRIVATE_removedDocumentsTs","__PRIVATE_startTs","__PRIVATE_sequenceNumbers","__PRIVATE_numTargetsRemoved","__PRIVATE_IndexedDbLruDelegateImpl","__PRIVATE_docCountPromise","__PRIVATE_orphanedDocumentCount","getTargetCache","__PRIVATE_docCount","__PRIVATE_orphanedCount","__PRIVATE_forEachOrphanedDocument","__PRIVATE_writeSentinelKey","__PRIVATE_isPinned","__PRIVATE_changeBuffer","getRemoteDocumentCache","newChangeBuffer","__PRIVATE_documentCount","getEntry","removeEntry","updateLimboDocument","__PRIVATE_nextPath","__PRIVATE_nextToReport","getSize","RemoteDocumentChangeBuffer","changesApplied","addEntry","assertNotApplied","newInvalidDocument","__PRIVATE_bufferedEntry","getFromCache","getAllFromCache","__PRIVATE_IndexedDbRemoteDocumentCacheImpl","setIndexManager","__PRIVATE_remoteDocumentsStore","updateMetadata","__PRIVATE_sizeDelta","getMetadata","byteSize","__PRIVATE_setMetadata","__PRIVATE_dbKey","__PRIVATE_dbRemoteDoc","__PRIVATE_maybeDecodeDocument","__PRIVATE_getSizedEntry","__PRIVATE_forEachDbEntry","__PRIVATE_getSizedEntries","__PRIVATE_sizeMap","__PRIVATE_dbKeyComparator","__PRIVATE_keyIter","__PRIVATE_potentialKey","getDocumentsMatchingQuery","mutatedDocs","__PRIVATE_endKey","__PRIVATE_dbRemoteDocs","incrementDocumentReadCount","getAllFromCollectionGroup","__PRIVATE_dbCollectionGroupKey","__PRIVATE_IndexedDbRemoteDocumentChangeBuffer","trackRemovals","__PRIVATE_documentGlobalStore","newUnknownDocument","__PRIVATE_dbTimestampKey","__PRIVATE_fromDbRemoteDocument","__PRIVATE_newIndexedDbRemoteDocumentCache","__PRIVATE_documentCache","__PRIVATE_documentStates","documentChange","__PRIVATE_previousDoc","__PRIVATE_deletedDoc","__PRIVATE_getResult","OverlayedDocument","LocalDocumentsView","remoteDocumentCache","mutationQueue","documentOverlayCache","getDocument","getDocuments","getLocalViewOfDocuments","existenceStateChanged","populateOverlays","computeViews","__PRIVATE_computeViewsResult","getOverlayedDocuments","__PRIVATE_missingOverlays","__PRIVATE_recalculateDocuments","recalculateAndSaveOverlays","__PRIVATE_recalculatedFields","__PRIVATE_masks","__PRIVATE_documentsByBatchId","key1","key2","__PRIVATE_processed","__PRIVATE_batches","__PRIVATE_newSet","__PRIVATE_baseDoc","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","__PRIVATE_originalDocs","__PRIVATE_overlaysPromise","__PRIVATE_modifiedDocs","__PRIVATE_localDocs","__PRIVATE_parents","__PRIVATE_collectionQuery","__PRIVATE_remoteDocuments","__PRIVATE_MemoryBundleCache","__PRIVATE_bundles","__PRIVATE_namedQueries","namedQuery","__PRIVATE_MemoryDocumentOverlayCache","__PRIVATE_overlayByBatchId","__PRIVATE_immediateChildrenPathLength","__PRIVATE_batchIdToOverlays","__PRIVATE_overlaysForBatchId","__PRIVATE_batchIter","__PRIVATE_existing","__PRIVATE_ReferenceSet","__PRIVATE_refsByKey","__PRIVATE_DocReference","__PRIVATE_compareByKey","__PRIVATE_refsByTarget","__PRIVATE_compareByTargetId","__PRIVATE_addReferences","__PRIVATE_removeRef","__PRIVATE_removeReferences","__PRIVATE_removeReferencesForId","__PRIVATE_emptyKey","__PRIVATE_startRef","__PRIVATE_endRef","__PRIVATE_removeAllReferences","__PRIVATE_referencesForId","__PRIVATE_firstRef","__PRIVATE_targetOrBatchId","__PRIVATE_MemoryMutationQueue","__PRIVATE_batchesByDocumentKey","__PRIVATE_findMutationBatch","__PRIVATE_rawIndex","__PRIVATE_indexOfBatchId","__PRIVATE_findMutationBatches","__PRIVATE_startPath","__PRIVATE_rowKeyPath","__PRIVATE_indexOfExistingBatchId","__PRIVATE_references","__PRIVATE_MemoryRemoteDocumentCacheImpl","__PRIVATE_sizer","__PRIVATE_previousSize","__PRIVATE_limti","__PRIVATE_forEachDocumentKey","__PRIVATE_MemoryRemoteDocumentChangeBuffer","__PRIVATE_MemoryTargetCache","__PRIVATE_highestSequenceNumber","__PRIVATE_forTargetCache","__PRIVATE_removals","__PRIVATE_matchingKeys","__PRIVATE_MemoryPersistence","__PRIVATE_referenceDelegateFactory","__PRIVATE_mutationQueues","__PRIVATE_listenSequence","__PRIVATE__started","__PRIVATE_targetCache","__PRIVATE_documentSize","__PRIVATE_bundleCache","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","__PRIVATE_queue","getBundleCache","transactionOperation","__PRIVATE_MemoryTransaction","__PRIVATE_onTransactionStarted","__PRIVATE_onTransactionCommitted","__PRIVATE_mutationQueuesContainKey","__PRIVATE_MemoryEagerDelegate","__PRIVATE_localViewReferences","__PRIVATE__orphanedDocuments","__PRIVATE_orphanedDocuments","fromPath","__PRIVATE_isReferenced","__PRIVATE_SchemaConverter","__PRIVATE_toVersion","autoIncrement","createIndex","unique","__PRIVATE_createQueryCache","deleteObjectStore","__PRIVATE_globalStore","__PRIVATE_existingMutations","__PRIVATE_v3MutationsStore","__PRIVATE_writeAll","__PRIVATE_removeAcknowledgedMutations","__PRIVATE_addDocumentGlobal","__PRIVATE_ensureSequenceNumbers","__PRIVATE_createCollectionParentIndex","__PRIVATE_rewriteCanonicalIds","__PRIVATE_remoteDocumentStore","__PRIVATE_rewriteRemoteDocumentCache","__PRIVATE_runOverlayMigration","__PRIVATE_queuesStore","__PRIVATE_queues","__PRIVATE_documentsStore","__PRIVATE_docSentinelKey","__PRIVATE_maybeSentinel","pathSegments","__PRIVATE_targetStore","__PRIVATE_originalDbTarget","__PRIVATE_originalTargetData","__PRIVATE_updatedDbTarget","__PRIVATE_legacyRemoteDocumentStore","__PRIVATE_legacyDocument","__PRIVATE_dbRemoteDocument","__PRIVATE_memoryPersistence","__PRIVATE_factory","__PRIVATE_userToDocumentSet","__PRIVATE_documentSet","__PRIVATE_allDocumentKeysForUser","__PRIVATE_forUser","__PRIVATE_PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","__PRIVATE_IndexedDbPersistence","allowTabSynchronization","clientId","__PRIVATE_lruParams","__PRIVATE_forceOwningTab","__PRIVATE_schemaVersion","isPrimary","networkEnabled","__PRIVATE_windowUnloadHandler","inForeground","__PRIVATE_documentVisibilityHandler","__PRIVATE_clientMetadataRefresher","__PRIVATE_lastGarbageCollectionTime","__PRIVATE_primaryStateListener","__PRIVATE_isAvailable","__PRIVATE_dbName","__PRIVATE_simpleDb","__PRIVATE_webStorage","__PRIVATE_updateClientMetadataAndTryBecomePrimary","__PRIVATE_attachVisibilityHandler","__PRIVATE_attachWindowUnloadHook","__PRIVATE_scheduleClientMetadataAndPrimaryLeaseRefreshes","__PRIVATE_setPrimaryStateListener","__PRIVATE_primaryState","databaseDeletedListener","enqueueAndForget","__PRIVATE_clientMetadataStore","updateTimeMs","__PRIVATE_verifyPrimaryLease","__PRIVATE_success","__PRIVATE_canActAsPrimary","__PRIVATE_releasePrimaryLeaseIfHeld","__PRIVATE_acquireOrExtendPrimaryLease","__PRIVATE_primaryClientStore","__PRIVATE_primaryClient","__PRIVATE_isLocalClient","__PRIVATE_removeClientMetadata","__PRIVATE_isWithinAge","__PRIVATE_inactiveClients","__PRIVATE_metadataStore","__PRIVATE_existingClients","__PRIVATE_filterActiveClients","__PRIVATE_inactive","__PRIVATE_client","__PRIVATE_inactiveClient","__PRIVATE_zombiedClientLocalStorageKey","__PRIVATE_maybeGarbageCollectMultiClientState","ownerId","__PRIVATE_currentPrimary","leaseTimestampMs","__PRIVATE_isClientZombied","__PRIVATE_otherClient","__PRIVATE_otherClientHasBetterNetworkState","__PRIVATE_otherClientHasBetterVisibility","__PRIVATE_otherClientHasSameNetworkState","__PRIVATE_markClientZombied","__PRIVATE_detachVisibilityHandler","__PRIVATE_detachWindowUnloadHook","__PRIVATE_simpleDbTxn","__PRIVATE_persistenceTransaction","__PRIVATE_removeClientZombiedEntry","__PRIVATE_clients","__PRIVATE_activityThresholdMs","__PRIVATE_getActiveClients","__PRIVATE_clientMetadata","__PRIVATE_simpleDbMode","__PRIVATE_holdsPrimaryLease","__PRIVATE_verifyAllowTabSynchronization","__PRIVATE_newPrimary","__PRIVATE_maxAgeMs","__PRIVATE_safariIndexdbBugVersionRegex","appVersion","enterRestrictedMode","__PRIVATE_isZombied","__PRIVATE_indexedDbStoragePrefix","__PRIVATE_LocalViewChanges","fromCache","__PRIVATE_addedKeys","__PRIVATE_removedKeys","__PRIVATE_viewSnapshot","docChanges","QueryContext","_documentReadCount","documentReadCount","__PRIVATE_QueryEngine","__PRIVATE_initialized","__PRIVATE_indexAutoCreationEnabled","__PRIVATE_indexAutoCreationMinCollectionSize","__PRIVATE_relativeIndexReadCostPerDocument","__PRIVATE_localDocumentsView","__PRIVATE_remoteKeys","__PRIVATE_queryResult","__PRIVATE_performQueryUsingIndex","__PRIVATE_performQueryUsingRemoteKeys","__PRIVATE_executeFullCollectionScan","__PRIVATE_createCacheIndexes","__PRIVATE_resultSize","__PRIVATE_indexedDocuments","__PRIVATE_previousResults","__PRIVATE_applyQuery","__PRIVATE_needsRefill","__PRIVATE_appendRemainingResults","__PRIVATE_queryResults","__PRIVATE_maybeDoc","__PRIVATE_sortedPreviousResults","__PRIVATE_limboFreeSnapshotVersion","__PRIVATE_docAtLimitEdge","__PRIVATE_indexedResults","__PRIVATE_remainingResults","__PRIVATE_LocalStoreImpl","__PRIVATE_queryEngine","initialUser","__PRIVATE_targetDataByTarget","__PRIVATE_targetIdByTarget","__PRIVATE_collectionGroupReadTime","__PRIVATE_initializeUserComponents","__PRIVATE_newLocalStore","__PRIVATE_localStoreHandleUserChange","__PRIVATE_localStoreImpl","__PRIVATE_oldBatches","__PRIVATE_promisedOldBatches","__PRIVATE_newBatches","removedBatchIds","addedBatchIds","__PRIVATE_changedKeys","__PRIVATE_affectedDocuments","__PRIVATE_localStoreGetLastRemoteSnapshotVersion","__PRIVATE_localStoreApplyRemoteEventToLocalCache","__PRIVATE_remoteVersion","__PRIVATE_newTargetDataByTargetMap","__PRIVATE_documentBuffer","__PRIVATE_change","__PRIVATE_oldTargetData","__PRIVATE_newTargetData","__PRIVATE_changedDocs","__PRIVATE_existenceChangedKeys","__PRIVATE_populateDocumentChangeBuffer","__PRIVATE_changedDocuments","__PRIVATE_updateRemoteVersion","__PRIVATE_updatedKeys","__PRIVATE_existingDocs","__PRIVATE_existingDoc","__PRIVATE_localStoreAllocateTarget","__PRIVATE_cached","__PRIVATE_cachedTargetData","__PRIVATE_localStoreReleaseTarget","__PRIVATE_keepPersistedTargetData","__PRIVATE_localStoreExecuteQuery","__PRIVATE_usePreviousResults","__PRIVATE_localStoreGetTargetData","__PRIVATE_setMaxReadTime","__PRIVATE_localStoreGetCachedTarget","__PRIVATE_targetCacheImpl","__PRIVATE_localStoreGetNewDocumentChanges","createWebStorageClientStateKey","createWebStorageMutationBatchKey","__PRIVATE_mutationKey","createWebStorageQueryTargetMetadataKey","__PRIVATE_MutationMetadata","__PRIVATE_mutationBatch","__PRIVATE_firestoreError","__PRIVATE_validData","__PRIVATE_toWebStorageJSON","__PRIVATE_batchMetadata","__PRIVATE_QueryTargetMetadata","__PRIVATE_RemoteClientState","__PRIVATE_clientState","__PRIVATE_activeTargetIdsSet","__PRIVATE_SharedOnlineState","onlineState","__PRIVATE_LocalClientState","__PRIVATE_addQueryTarget","__PRIVATE_removeQueryTarget","__PRIVATE_WebStorageSharedClientState","__PRIVATE_localClientId","syncEngine","onlineStateHandler","__PRIVATE_storageListener","__PRIVATE_handleWebStorageEvent","__PRIVATE_activeClients","__PRIVATE_earlyEvents","__PRIVATE_escapedPersistenceKey","__PRIVATE_localClientStorageKey","__PRIVATE_sequenceNumberKey","__PRIVATE_clientStateKeyRe","__PRIVATE_mutationBatchKeyRe","__PRIVATE_queryTargetKeyRe","__PRIVATE_onlineStateKey","__PRIVATE_bundleLoadedKey","__PRIVATE_storageItem","__PRIVATE_fromWebStorageEntry","__PRIVATE_persistClientState","__PRIVATE_onlineStateJSON","__PRIVATE_fromWebStorageOnlineState","__PRIVATE_handleOnlineStateEvent","getAllActiveQueryTargets","__PRIVATE_extractActiveQueryTargets","isActiveQueryTarget","addPendingMutation","__PRIVATE_persistMutationState","updateMutationState","__PRIVATE_removeMutationState","addLocalQueryTarget","__PRIVATE_queryState","__PRIVATE_localClientState","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","updateQueryState","__PRIVATE_persistQueryTargetState","handleUserChange","setOnlineState","__PRIVATE_persistOnlineState","notifyBundleLoaded","collectionGroups","__PRIVATE_persistBundleLoadedState","__PRIVATE_storageEvent","storageArea","__PRIVATE_fromWebStorageClientStateKey","__PRIVATE_handleClientStateEvent","__PRIVATE_fromWebStorageClientState","__PRIVATE_mutationMetadata","__PRIVATE_fromWebStorageMutationMetadata","__PRIVATE_handleMutationBatchEvent","__PRIVATE_queryTargetMetadata","__PRIVATE_fromWebStorageQueryTargetMetadata","__PRIVATE_handleQueryTargetEvent","__PRIVATE_seqString","__PRIVATE_parsed","__PRIVATE_fromWebStoreBundleLoadedState","__PRIVATE_cg","__PRIVATE_synchronizeWithChangedDocuments","__PRIVATE_mutationState","__PRIVATE_targetKey","__PRIVATE_targetMetadata","__PRIVATE_applyBatchState","__PRIVATE_applyTargetState","__PRIVATE_updatedClients","__PRIVATE_existingTargets","__PRIVATE_newTargets","__PRIVATE_addedTargets","__PRIVATE_removedTargets","__PRIVATE_applyActiveTargetsChange","__PRIVATE_activeTargets","__PRIVATE_kev","__PRIVATE_MemorySharedClientState","__PRIVATE_localState","__PRIVATE_NoopConnectivityMonitor","__PRIVATE_addCallback","__PRIVATE_BrowserConnectivityMonitor","__PRIVATE_networkAvailableListener","__PRIVATE_onNetworkAvailable","__PRIVATE_networkUnavailableListener","__PRIVATE_onNetworkUnavailable","__PRIVATE_callbacks","__PRIVATE_configureNetworkMonitoring","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_maxResult","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_StreamBridge","__PRIVATE_sendFn","__PRIVATE_closeFn","__PRIVATE_onOpen","__PRIVATE_wrappedOnOpen","__PRIVATE_onClose","__PRIVATE_wrappedOnClose","__PRIVATE_wrappedOnMessage","__PRIVATE_callOnOpen","__PRIVATE_callOnClose","__PRIVATE_callOnMessage","__PRIVATE_LOG_TAG","__PRIVATE_WebChannelConnection","databaseInfo","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_shouldResourcePathBeIncludedInRequest","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","__PRIVATE_makeUrl","google-cloud-resource-prefix","x-goog-request-params","__PRIVATE_modifyHeadersForRequest","__PRIVATE_performRPCRequest","__PRIVATE_invokeStreamingRPC","__PRIVATE_expectedResponseCount","__PRIVATE_urlRpcName","terminate","__PRIVATE_xhr","__PRIVATE_responseError","__PRIVATE_firestoreErrorCode","__PRIVATE_serverError","__PRIVATE_requestString","__PRIVATE_openStream","__PRIVATE_urlParts","__PRIVATE_webchannelTransport","__PRIVATE_requestStats","forwardChannelRequestTimeoutMs","__PRIVATE_longPollingTimeoutSeconds","timeoutSeconds","__PRIVATE_opened","__PRIVATE_streamBridge","__PRIVATE_unguardedEventListen","WebChannel","__PRIVATE_msgData","__PRIVATE_getWindow","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","__PRIVATE_lastAttemptTime","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_remainingDelayMs","__PRIVATE_skipBackoff","skipDelay","__PRIVATE_PersistentStream","__PRIVATE_connectionTimerId","__PRIVATE_idleTimerId","__PRIVATE_healthTimerId","authCredentialsProvider","appCheckCredentialsProvider","__PRIVATE_closeCount","__PRIVATE_idleTimer","__PRIVATE_healthCheck","__PRIVATE_backoff","__PRIVATE_isStarted","__PRIVATE_isOpen","__PRIVATE_performBackoff","__PRIVATE_inhibitBackoff","__PRIVATE_markIdle","__PRIVATE_handleIdleCloseTimer","__PRIVATE_sendRequest","__PRIVATE_cancelIdleCheck","__PRIVATE_cancelHealthCheck","__PRIVATE_finalState","__PRIVATE_tearDown","__PRIVATE_dispatchIfNotClosed","__PRIVATE_getCloseGuardedDispatcher","__PRIVATE_startStream","__PRIVATE_rpcError","__PRIVATE_handleStreamClose","__PRIVATE_startRpc","__PRIVATE_startCloseCount","__PRIVATE_PersistentListenStream","authCredentials","appCheckCredentials","__PRIVATE_watchChangeProto","targetChangeType","__PRIVATE_causeProto","__PRIVATE_entityChange","documentDelete","__PRIVATE_docDelete","documentRemove","__PRIVATE_docRemove","__PRIVATE_fromWatchChange","__PRIVATE_onWatchChange","__PRIVATE_watch","addTarget","labels","goog-listen-tags","__PRIVATE_unwatch","__PRIVATE_PersistentWriteStream","__PRIVATE_handshakeComplete_","__PRIVATE_handshakeComplete","__PRIVATE_writeMutations","__PRIVATE_responseProto","streamToken","writeResults","commitTime","__PRIVATE_onMutationResult","__PRIVATE_onHandshakeComplete","__PRIVATE_writeHandshake","__PRIVATE_DatastoreImpl","__PRIVATE_terminated","__PRIVATE_verifyInitialized","__PRIVATE_OnlineStateTracker","__PRIVATE_watchStreamFailures","__PRIVATE_onlineStateTimer","__PRIVATE_shouldWarnClientIsOffline","__PRIVATE_handleWatchStreamStart","__PRIVATE_setAndBroadcast","__PRIVATE_logClientOfflineWarningIfNecessary","__PRIVATE_handleWatchStreamFailure","__PRIVATE_clearOnlineStateTimer","__PRIVATE_newState","__PRIVATE_RemoteStoreImpl","datastore","__PRIVATE_connectivityMonitor","remoteSyncer","__PRIVATE_writePipeline","__PRIVATE_listenTargets","__PRIVATE_offlineCauses","__PRIVATE_onNetworkStatusChange","__PRIVATE_canUseNetwork","remoteStore","__PRIVATE_remoteStoreImpl","__PRIVATE_disableNetworkInternal","__PRIVATE_onlineStateTracker","__PRIVATE_enableNetworkInternal","__PRIVATE_networkStatusHandler","__PRIVATE_remoteStoreListen","__PRIVATE_shouldStartWatchStream","__PRIVATE_startWatchStream","__PRIVATE_ensureWatchStream","__PRIVATE_sendWatchRequest","__PRIVATE_remoteStoreUnlisten","__PRIVATE_watchStream","__PRIVATE_sendUnwatchRequest","__PRIVATE_watchChangeAggregator","__PRIVATE_cleanUpWatchStreamState","__PRIVATE_disableNetworkUntilRecovery","__PRIVATE_executeWithRecovery","__PRIVATE_fillWritePipeline","__PRIVATE_writeStream","__PRIVATE_ensureWriteStream","__PRIVATE_lastBatchIdRetrieved","__PRIVATE_afterBatchId","__PRIVATE_localStoreGetNextMutationBatch","__PRIVATE_addToWritePipeline","__PRIVATE_shouldStartWriteStream","__PRIVATE_startWriteStream","__PRIVATE_onWriteStreamClose","rejectFailedWrite","__PRIVATE_remoteStoreHandleCredentialChange","verifyOperationInProgress","__PRIVATE_usesNetwork","handleCredentialChange","__PRIVATE_remoteStoreApplyPrimaryState","__PRIVATE_datastoreImpl","rejectListen","__PRIVATE_targetPurpose","__PRIVATE_requestTargetData","applyRemoteEvent","applySuccessfulWrite","DelayedOperation","targetTimeMs","removalCallback","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","handleDelayElapsed","__PRIVATE_wrapInUserErrorIfRecoverable","DocumentSet","keyedMap","sortedSet","oldSet","__PRIVATE_thisDoc","__PRIVATE_otherDoc","__PRIVATE_docStrings","__PRIVATE_DocumentChangeSet","__PRIVATE_changeMap","track","__PRIVATE_oldChange","__PRIVATE_getChanges","ViewSnapshot","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","emptySet","__PRIVATE_otherChanges","__PRIVATE_QueryListenersInfo","__PRIVATE_viewSnap","__PRIVATE_listeners","__PRIVATE_EventManagerImpl","__PRIVATE_snapshotsInSyncListeners","__PRIVATE_eventManagerListen","__PRIVATE_eventManagerImpl","__PRIVATE_firstListen","__PRIVATE_queryInfo","onListen","__PRIVATE_applyOnlineStateChange","__PRIVATE_onViewSnapshot","__PRIVATE_raiseSnapshotsInSyncEvent","__PRIVATE_eventManagerUnlisten","__PRIVATE_lastListen","onUnlisten","__PRIVATE_QueryListener","__PRIVATE_queryObserver","__PRIVATE_raisedInitialEvent","__PRIVATE_snap","includeMetadataChanges","__PRIVATE_raisedEvent","__PRIVATE_shouldRaiseEvent","__PRIVATE_shouldRaiseInitialEvent","__PRIVATE_raiseInitialEvent","__PRIVATE_waitForSyncWhenOnline","__PRIVATE_hasPendingWritesChanged","fromInitialDocuments","__PRIVATE_SizedBundleElement","__PRIVATE_payload","byteLength","__PRIVATE_isBundleMetadata","__PRIVATE_BundleConverterImpl","__PRIVATE_toDocumentKey","__PRIVATE_toMutableDocument","__PRIVATE_bundledDoc","__PRIVATE_toSnapshotVersion","__PRIVATE_BundleLoader","progress","__PRIVATE_bundleInitialProgress","__PRIVATE_addSizedElement","bytesLoaded","documentsLoaded","documentMetadata","__PRIVATE_getQueryDocumentMapping","__PRIVATE_queryDocumentMap","__PRIVATE_bundleConverter","__PRIVATE_bundleDoc","__PRIVATE_bundleName","__PRIVATE_umbrellaTargetData","__PRIVATE_documentChangeResult","__PRIVATE_localStoreApplyBundledDocuments","__PRIVATE_allocated","__PRIVATE_localStoreSaveNamedQuery","taskState","__PRIVATE_changedCollectionGroups","totalDocuments","totalBytes","__PRIVATE_AddedLimboDocument","__PRIVATE_RemovedLimboDocument","__PRIVATE_View","__PRIVATE__syncedDocuments","__PRIVATE_syncState","__PRIVATE_limboDocuments","__PRIVATE_docComparator","__PRIVATE_syncedDocuments","__PRIVATE_computeDocChanges","__PRIVATE_previousChanges","__PRIVATE_changeSet","__PRIVATE_oldDocumentSet","__PRIVATE_newMutatedKeys","__PRIVATE_newDocumentSet","__PRIVATE_lastDocInLimit","__PRIVATE_firstDocInLimit","__PRIVATE_oldDoc","__PRIVATE_oldDocHadPendingMutations","__PRIVATE_newDocHasPendingMutations","__PRIVATE_changeApplied","__PRIVATE_shouldWaitForSyncedDocument","__PRIVATE_limboResolutionEnabled","__PRIVATE_targetIsPendingReset","__PRIVATE_c1","__PRIVATE_c2","__PRIVATE_applyTargetChange","__PRIVATE_limboChanges","__PRIVATE_updateLimboDocuments","__PRIVATE_newSyncState","__PRIVATE_shouldBeInLimbo","__PRIVATE_oldLimboDocuments","__PRIVATE_synchronizeWithPersistedState","__PRIVATE_computeInitialSnapshot","__PRIVATE_QueryView","LimboResolution","__PRIVATE_receivedDocument","__PRIVATE_SyncEngineImpl","sharedClientState","maxConcurrentLimboResolutions","__PRIVATE_syncEngineListener","__PRIVATE_queryViewsByQuery","__PRIVATE_queriesByTarget","__PRIVATE_enqueuedLimboResolutions","__PRIVATE_activeLimboTargetsByKey","__PRIVATE_activeLimboResolutionsByTarget","__PRIVATE_limboDocumentRefs","__PRIVATE_mutationUserCallbacks","__PRIVATE_pendingWritesCallbacks","__PRIVATE_limboTargetIdGenerator","__PRIVATE_forSyncEngine","__PRIVATE__isPrimaryClient","isPrimaryClient","__PRIVATE_initializeViewAndComputeSnapshot","__PRIVATE_syncEngineImpl","__PRIVATE_applyDocChanges","__PRIVATE_queryView","__PRIVATE_viewDocChanges","__PRIVATE_viewChange","__PRIVATE_updateTrackedLimbos","__PRIVATE_synthesizedTargetChange","__PRIVATE_syncEngineWrite","__PRIVATE_userCallback","__PRIVATE_syncEngineEnsureWriteCallbacks","__PRIVATE_overlayedDocuments","__PRIVATE_remoteDocs","__PRIVATE_docsWithoutRemoteVersion","__PRIVATE_baseObject","__PRIVATE_existingValue","__PRIVATE_coercedValue","__PRIVATE_mutationExtractBaseValue","__PRIVATE_extractFieldMask","__PRIVATE_currentPath","__PRIVATE_nestedFields","__PRIVATE_nestedPath","__PRIVATE_newCallbacks","__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore","__PRIVATE_syncEngineApplyRemoteEvent","__PRIVATE_limboResolution","__PRIVATE_syncEngineApplyOnlineStateChange","__PRIVATE_newViewSnapshots","__PRIVATE_syncEngineApplySuccessfulWrite","__PRIVATE_mutationBatchResult","__PRIVATE_affected","__PRIVATE_docKeys","__PRIVATE_promiseChain","__PRIVATE_ackVersion","__PRIVATE_localStoreAcknowledgeBatch","__PRIVATE_processUserCallback","__PRIVATE_triggerPendingWritesCallbacks","__PRIVATE_removeAndCleanupTarget","__PRIVATE_onWatchError","__PRIVATE_limboKey","__PRIVATE_removeLimboTarget","__PRIVATE_limboTargetId","__PRIVATE_pumpEnqueuedLimboResolutions","__PRIVATE_limboChange","__PRIVATE_keyString","__PRIVATE_trackLimboChange","__PRIVATE_newSnaps","__PRIVATE_docChangesInAllViews","__PRIVATE_queriesProcessed","__PRIVATE_fromSnapshot","__PRIVATE_viewChanges","__PRIVATE_updatedTargetData","__PRIVATE_syncEngineApplyPrimaryState","__PRIVATE_ensureWatchCallbacks","__PRIVATE_activeQueries","__PRIVATE_synchronizeQueryViewsAndRaiseSnapshots","__PRIVATE_synthesizeTargetToQuery","__PRIVATE_keySet","__PRIVATE_syncEngineRejectListen","__PRIVATE_viewSnaps","__PRIVATE_eventManagerOnWatchError","__PRIVATE_affectedKeys","MemoryOfflineComponentProvider","synchronizeTabs","cfg","createSharedClientState","createPersistence","createLocalStore","gcScheduler","createGarbageCollectionScheduler","indexBackfillerScheduler","createIndexBackfillerScheduler","__PRIVATE_IndexedDbOfflineComponentProvider","__PRIVATE_onlineComponentProvider","cacheSizeBytes","forceOwnership","__PRIVATE_indexBackfiller","withCacheSize","__PRIVATE_MultiTabOfflineComponentProvider","__PRIVATE_syncEngineApplyBatchState","__PRIVATE_batchState","__PRIVATE_mutationQueueImpl","__PRIVATE_syncEngineApplyTargetState","__PRIVATE_synthesizedRemoteEvent","createSynthesizedRemoteEventForCurrentChange","__PRIVATE_syncEngineApplyActiveTargetsChange","__PRIVATE_syncEngineSynchronizeWithChangedDocuments","OnlineComponentProvider","offlineComponentProvider","createDatastore","createRemoteStore","createEventManager","createSyncEngine","__PRIVATE_errorMessage","startAsPrimary","__PRIVATE_newSyncEngine","__PRIVATE_toByteStreamReaderHelper","__PRIVATE_bytesPerRead","__PRIVATE_readFrom","releaseLock","__PRIVATE_AsyncObserver","muted","__PRIVATE_scheduleEvent","__PRIVATE_mute","__PRIVATE_eventHandler","__PRIVATE_BundleReaderImpl","__PRIVATE_reader","__PRIVATE_textDecoder","__PRIVATE_nextElementImpl","__PRIVATE_lengthBuffer","__PRIVATE_readLength","__PRIVATE_lengthString","__PRIVATE_raiseError","__PRIVATE_jsonString","__PRIVATE_readJsonString","__PRIVATE_indexOfOpenBracket","__PRIVATE_pullMoreDataToBuffer","Transaction","readVersions","lastTransactionError","writtenDocs","ensureCommitNotCalled","missing","recordVersion","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_docVersion","__PRIVATE_existingVersion","__PRIVATE_TransactionRunner","updateFunction","__PRIVATE_attemptsRemaining","maxAttempts","__PRIVATE_run","__PRIVATE_runWithBackOff","__PRIVATE_tryRunUpdateFunction","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","FirestoreClient","newId","authCredentialListener","appCheckCredentialListener","__PRIVATE_newAppCheckToken","configuration","setCredentialChangeListener","setAppCheckTokenChangeListener","verifyNotTerminated","isShuttingDown","enqueueAndForgetEvenWhileRestricted","_onlineComponents","_offlineComponents","__PRIVATE_setOfflineComponentProvider","__PRIVATE_setOnlineComponentProvider","__PRIVATE_ensureOfflineComponents","__PRIVATE_canFallbackFromIndexedDbError","_uninitializedComponentsProvider","_offline","__PRIVATE_ensureOnlineComponents","_online","__PRIVATE_getPersistence","__PRIVATE_getLocalStore","__PRIVATE_getRemoteStore","__PRIVATE_getSyncEngine","__PRIVATE_getEventManager","__PRIVATE_firestoreClientGetDocumentViaSnapshotListener","__PRIVATE_wrappedObserver","__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener","__PRIVATE_firestoreClientLoadBundle","__PRIVATE_resultTask","__PRIVATE_syncEngineLoadBundle","__PRIVATE_bundleReader","__PRIVATE_currentReadTime","_completeWith","_updateProgress","__PRIVATE_loader","__PRIVATE_nextElement","_failWith","__PRIVATE_cloneLongPollingOptions","__PRIVATE_datastoreInstances","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_valueDescription","__PRIVATE_customObjectName","__PRIVATE_cast","description","__PRIVATE_validatePositiveNumber","FirestoreSettingsImpl","ignoreUndefinedProperties","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","__PRIVATE_options1","__PRIVATE_options2","Firestore","_authCredentials","_appCheckCredentials","_databaseId","_persistenceKey","_settings","_settingsFrozen","_initialized","_terminated","_terminateTask","_setSettings","sessionIndex","iamToken","authTokenFactory","client","_getSettings","_freezeSettings","_terminate","firestore","converter","_query","withConverter","DocumentReference","CollectionReference","__PRIVATE_absolutePath","refEqual","queryEqual","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","enqueue","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","purgeExistingTasks","__PRIVATE_retryNextOp","__PRIVATE_newTail","createAndSchedule","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","__PRIVATE_drain","__PRIVATE_skipDelaysForTimerId","__PRIVATE_isPartialObserver","__PRIVATE_methods","LoadBundleTask","_progressObserver","_taskCompletionResolver","_lastProgress","onProgress","onRejected","onFulfilled","firestoreFactory","__PRIVATE_LiteFirestore","_queue","_firestoreClient","__PRIVATE_configureFirestore","ensureFirestoreConfigured","_offlineComponentProvider","_onlineComponentProvider","_offlineKind","__PRIVATE_setPersistenceProviders","__PRIVATE_persistenceResult","waitForPendingWrites","__PRIVATE_highestBatchId","__PRIVATE_syncEngineRegisterPendingWritesCallback","enableNetwork","disableNetwork","__PRIVATE_verifyNotInitialized","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","FieldValue","_methodName","GeoPoint","_lat","_long","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","__PRIVATE_hasConverter","__PRIVATE_targetDoc","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_fieldValue","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_entryIndex","__PRIVATE_parsedEntry","fromDate","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_FIELD_PATH_RESERVED","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_userDataWriter","_document","_converter","QueryDocumentSnapshot","fromFirestore","convertValue","__PRIVATE_validateHasExplicitOrderByForLimitToLast","AppliableConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","_field","_op","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_testQuery","_getQueryConstraints","QueryOrderByConstraint","_direction","__PRIVATE_newOrderBy","QueryLimitConstraint","_limitType","_docOrFields","_inclusive","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_docOrFields","components","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","operator","__PRIVATE_conflictingOp","__PRIVATE_operators","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertObjectMap","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","toFirestore","__PRIVATE_LiteUserDataWriter","SnapshotMetadata","__PRIVATE_LiteDocumentSnapshot","userDataWriter","_firestoreImpl","serverTimestamps","QuerySnapshot","_snapshot","thisArg","_cachedChanges","_cachedChangesIncludeMetadataChanges","__PRIVATE_querySnapshot","oldIndex","__PRIVATE_indexTracker","__PRIVATE_resultChangeType","snapshotEqual","__PRIVATE_ExpUserDataWriter","getDocFromCache","reference","__PRIVATE_firestoreClientGetDocumentFromLocalCache","getDocsFromCache","__PRIVATE_firestoreClientGetDocumentsFromLocalCache","setDoc","__PRIVATE_convertedValue","executeWrite","updateDoc","__PRIVATE_fieldOrUpdateData","onSnapshot","__PRIVATE_currArg","__PRIVATE_internalOptions","__PRIVATE_userObserver","__PRIVATE_internalQuery","__PRIVATE_convertToDocSnapshot","onSnapshotsInSync","__PRIVATE_firestoreClientAddSnapshotsInSyncListener","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","_transaction","lookup","__PRIVATE_liteDocumentSnapshot","__PRIVATE_optionsWithDefaults","__PRIVATE_firestoreClientTransaction","__PRIVATE_internalTransaction","__PRIVATE_firestoreInstance","validateSetOptions","assertUint8ArrayAvailable","assertBase64Available","Blob","isPartialObserver","IndexedDbPersistenceProvider","enableIndexedDbPersistence","persistenceSettings","enableMultiTabIndexedDbPersistence","clearIndexedDbPersistence","databaseIdOrApp","_persistenceProvider","_DatabaseId","_appCompat","settingsLiteral","currentSettings","__PRIVATE_newHostSetting","connectFirestoreEmulator","enablePersistence","experimentalForceOwningTab","_validateIsNotUsedTogether","clearPersistence","replaceFunctionName","ExpWriteBatch","loadBundle","bundleData","expQuery","UserDataWriter","forKey","castReference","ExpDocumentSnapshot","dataOrField","FirestoreDataConverter","ExpQueryDocumentSnapshot","modelObject","converterMapByFirestore","INSTANCES","untypedConverterByConverter","forPath","ExpDocumentReference","_DocumentKey","fieldOrUpdateData","extractSnapshotOptions","wrapObserver","wrapper","userObserver","opStr","directionStr","ExpQuerySnapshot","DocumentChange","docChange","docRef","__PRIVATE_docRef","addDoc","_cast","firestoreNamespace","ExpFieldPath","InternalFieldPath","serverTimestamp","delegate","arrayRemove","firestoreExp","LONG_TYPE","UNSIGNED_LONG_TYPE","mapValues","FUNCTIONS_TYPE","errorCodeMap","FunctionsError","_errorForResponse","bodyJSON","codeForHTTPStatus","errorJSON","ContextProvider","messagingProvider","messaging","getAuthToken","getMessagingToken","Notification","permission","getAppCheckToken","limitedUseAppCheckTokens","messagingToken","DEFAULT_REGION","FunctionsService","regionOrCustomDomain","emulatorOrigin","contextProvider","cancelAllRequests","deleteService","customDomain","region","_url","httpsCallable","functionsInstance","callAtURL","failAfterHandle","millis","failAfter","postJSON","responseData","connectFunctionsEmulator","httpsCallableFromURL","MessageType","_region","_customDomain","_httpsCallable","httpsCallableFromURLExp","useFunctionsEmulator","useFunctionsEmulatorExp","functionsServiceExp","Functions","DEFAULT_SW_PATH","DEFAULT_SW_SCOPE","DEFAULT_VAPID_KEY","ENDPOINT","CONSOLE_CAMPAIGN_ID","CONSOLE_CAMPAIGN_ANALYTICS_ENABLED","arrayToBase64","uint8Array","base64String","OLD_DB_NAME","OLD_OBJECT_STORE_NAME","migrateOldDatabase","senderId","databases","dbNames","tokenDetails","upgradeTransaction","oldDetails","p256dh","fcmToken","subscriptionOptions","swScope","vapidKey","checkTokenDetails","DATABASE_NAME","DATABASE_VERSION","upgradeDb","dbGet","firebaseDependencies","oldTokenDetails","dbSet","only-available-in-window","only-available-in-sw","permission-default","permission-blocked","unsupported-browser","indexed-db-unsupported","failed-service-worker-registration","token-subscribe-failed","token-subscribe-no-token","token-unsubscribe-failed","token-update-failed","token-update-no-token","use-sw-after-get-token","invalid-sw-registration","invalid-bg-handler","invalid-vapid-key","use-vapid-key-after-get-token","requestDeleteToken","unsubscribeOptions","getEndpoint","x-goog-firebase-installations-auth","getBody","web","applicationPubKey","TOKEN_EXPIRATION_MS","pushSubscription","swRegistration","pushManager","getSubscription","userVisibleOnly","applicationServerKey","repeat","rawData","outputArray","base64ToArray","getPushSubscription","dbOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","updatedToken","updateOptions","requestUpdateToken","updatedTokenDetails","deleteTokenInternal","updateToken","getNewToken","dbRemove","subscribeOptions","requestGetToken","externalizePayload","internalPayload","icon","analyticsLabel","collapseKey","collapse_key","messageId","fcmMessageId","messagePayloadInternal","notification","title","image","fcmOptions","click_action","analytics_label","_mergeStrings","s1","s2","resultArray","MessagingService","analyticsProvider","deliveryMetricsExportedToBigQueryEnabled","onBackgroundMessageHandler","onMessageHandler","logEvents","isLogServiceStarted","messagingSenderId","registerDefaultSw","browserErrorMessage","requestPermission","ServiceWorkerRegistration","updateSwReg","serviceWorkerRegistration","logToScion","messageType","NOTIFICATION_CLICKED","PUSH_RECEIVED","message_id","message_name","message_time","message_device_time","messageEventListener","dataPayload","isFirebaseMessaging","WindowMessagingFactory","WindowMessagingInternalFactory","deleteToken","_deleteToken","_onMessage","FCM_MSG","SDK_PLATFORM_WEB","EVENT_MESSAGE_DELIVERED","stageLog","fcmEvent","project_number","instance_id","message_type","DISPLAY_NOTIFICATION","DATA_MESSAGE","sdk_platform","package_name","createFcmEvent","productId","event_time_ms","source_extension_json_proto3","compliance_data","complianceData","privacy_context","prequest","origin_associated_product_id","buildComplianceData","createAndEnqueueLogEvent","onPush","getMessagePayloadInternal","clientList","getClientList","sendMessagePayloadInternalToWindows","notificationPayloadInternal","actions","maxActions","showNotification","wrappedInternalPayload","wrapInternalPayload","onNotificationClick","stopImmediatePropagation","isConsoleMessage","getLink","originUrl","clientUrl","getWindowClient","clients","openWindow","matchAll","includeUncontrolled","SwMessagingFactory","waitUntil","newSubscription","onSubChange","onBackgroundMessage","_onBackgroundMessage","StorageErrorCode","MessagingCompatImpl","_getToken","messagingCompatFactory","NAMESPACE_EXPORTS","PushSubscription","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","StorageError","status_","prependCode","_baseMessage","_codeEquals","unknown","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","CANCELED","cannotSliceBlob","CANNOT_SLICE_BLOB","invalidArgument","appDeleted","APP_DELETED","invalidRootOperation","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","INTERNAL_ERROR","Location","bucket","isRoot","fullServerUrl","bucketOnlyServerUrl","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","INVALID_DEFAULT_BUCKET","bucketDomain","gsRegex","httpModify","loc","firebaseStorageHost","firebaseStorageRegExp","cloudStorageHost","groups","regex","indices","postModify","group","captures","bucketValue","pathValue","INVALID_URL","FailRequest","promise_","getPromise","_appDelete","isString","isNativeBlob","isNativeBlobDefined","validateNumber","argument","minValue","makeUrl","urlPart","makeQueryString","queryPart","nextPart","isRetryStatusCode","additionalRetryCodes","isFiveHundredCode","isExtraRetryCode","isAdditionalRetryCode","NetworkRequest","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","progressCallback_","connectionFactory_","retry","pendingConnection_","backoffId_","canceled_","appDelete_","resolve_","reject_","doTheRequest","backoffCallback","RequestEndStatus","progressListener","progressEvent","loaded","lengthComputable","addUploadProgressListener","removeUploadProgressListener","hitServer","getErrorCode","wasCanceled","successCode","backoffDone","requestWentThrough","wasSuccessCode","getErrorText","doRequest","backoffCompleteCb","waitSeconds","retryTimeoutId","globalTimeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","responseHandler","clearGlobalTimeout","waitMillis","stopped","wasTimeout","appDelete","getBlob","BlobBuilder","WebKitBlobBuilder","UNSUPPORTED_ENVIRONMENT","decodeBase64","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","StringData","contentType","dataFromString","stringData","utf8Bytes_","base64Bytes_","dataUrl","DataURLParts","percentEncodedBytes_","hi","lo","hasMinus","hasUnder","hasPlus","hasSlash","FbsBlob","elideCopy","blobType","data_","size_","startByte","endByte","realBlob","sliced","webkitSlice","mozSlice","blobby","uint8Arrays","finalLength","merged","uploadData","jsonObjectOrNull","lastComponent","lastIndexOf","noXform_","Mapping","server","local","writable","xform","mappings_","getMappings","mappings","nameMapping","_metadata","fullPath","sizeMapping","addRef","_makeStorageReference","fromResourceString","resourceString","resource","mapping","fromResource","toResourceString","PREFIXES_KEY","fromResponseString","listResult","items","nextPageToken","pathWithoutTrailingSlash","fromBackendResponse","RequestInfo","errorHandler","progressCallback","successCodes","handlerCheck","cndn","metadataHandler","listHandler","downloadUrlHandler","tokensList","alt","downloadUrlFromResourceString","_protocol","sharedErrorHandler","newErr","UNAUTHORIZED_APP","QUOTA_EXCEEDED","UNAUTHORIZED","objectErrorHandler","shared","OBJECT_NOT_FOUND","maxOperationRetryTime","requestInfo","metadataForUpload_","metadataClone","multipartUpload","X-Goog-Upload-Protocol","boundary","genBoundary","metadata_","preBlobPart","postBlobPart","maxUploadRetryTime","ResumableUploadStatus","checkResumeHeader_","allowed","allowedStatus","createResumableUpload","metadataForUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","getResumableUploadStatus","sizeString","continueResumableUpload","SERVER_FILE_WRONG_SIZE","bytesLeft","bytesToUpload","uploadCommand","X-Goog-Upload-Offset","uploadStatus","newCurrent","TaskEvent","STATE_CHANGED","TaskState","RUNNING","PAUSED","taskStateFromInternalTaskState","Observer","argsToForward","XhrTextConnection","sent_","initXhr","errorCode_","sendPromise_","upload","newTextConnection","UploadTask","_transferred","_needToFetchStatus","_needToFetchMetadata","_observers","_error","_uploadUrl","_request","_chunkMultiplier","_resolve","_ref","_blob","_mappings","_resumable","_shouldDoResumable","_state","_errorHandler","completeTransitions_","backoffExpired","isExponentialBackoffExpired","sleepTime","_transition","_metadataErrorHandler","maxSleepTime","_promise","_makeProgressCallback","sizeBefore","_createResumable","_fetchStatus","_fetchMetadata","pendingTimeout","_continueUpload","_oneShotUpload","_resolveToken","_getAuthToken","_location","createRequest","_makeRequest","statusRequest","uploadRequest","_increaseMultiplier","newStatus","metadataRequest","multipartRequest","transferred","old","_notifyObservers","wasPaused","externalState","bytesTransferred","_addObserver","_removeObserver","_notifyObserver","_finishPromise","triggered","fbsAsync","toCall","valid","pause","_service","_newRef","newPath","_throwIfRoot","listAll","listAllHelper","pageToken","nextPage","list","maxResults","delimiter","requestsList","makeRequestWithTokens","requestsUpdateMetadata","getDownloadURL","requestsGetDownloadUrl","NO_DOWNLOAD_URL","deleteObject","_xhr","_text","requestsDeleteObject","_getChild","canonicalChildPath","refFromPath","FirebaseStorageImpl","_bucket","NO_DEFAULT_BUCKET","serviceOrRef","pathOrUrl","extractBucket","_authProvider","_appCheckProvider","_firebaseVersion","_appId","_maxOperationRetryTime","_maxUploadRetryTime","_requests","_overrideAuthToken","tokenData","requestFactory","makeRequest","firebaseVersion","uploadBytesResumable","requestsGetMetadata","getMetadataInternal","refInternal","connectStorageEmulator","connectEmulatorInternal","UploadTaskSnapshotCompat","UploadTaskCompat","wrappedNextOrObserver","taskSnapshot","ListResultCompat","ReferenceCompat","_getChildInternal","putString","_dataFromString","_UploadTask","_FbsBlob","listAllInternal","listInternal","updateMetadataInternal","getDownloadURLInternal","deleteObjectInternal","_invalidRootOperation","StorageServiceCompat","isUrl","_invalidArgument","_Location","setMaxUploadRetryTime","setMaxOperationRetryTime","storageExp","Storage","TRACE_MEASURE_PREFIX","CONFIG_LOCAL_STORAGE_KEY","CONFIG_EXPIRY_LOCAL_STORAGE_KEY","VisibilityState","firebaseInstance","SERVICE_NAME","trace started","trace stopped","nonpositive trace startTime","nonpositive trace duration","no window","no app id","no project id","no api key","invalid cc log","FB not default","RC response not ok","invalid attribute name","invalid attribute value","invalid custom metric name","invalid String merger input","already initialized","consoleLogger","apiInstance","windowInstance","Api","PerformanceObserver","windowLocation","perfMetrics","onFirstInputDelay","getUrl","mark","measure","measureName","mark1","mark2","getEntriesByName","getTimeOrigin","timeOrigin","timing","navigationStart","requiredApisAvailable","setupObserver","entryType","observe","entryTypes","iid","mergeStrings","part1","part2","sizeDiff","settingsServiceInstance","SettingsService","instrumentationEnabled","dataCollectionEnabled","loggingEnabled","tracesSamplingRate","networkRequestsSamplingRate","logEndPointUrl","flTransportEndpointUrl","transportKey","logSource","logTraceAfterSampling","logNetworkAfterSampling","configTimeToLive","getFlTransportFullUrl","RESERVED_ATTRIBUTE_PREFIXES","ATTRIBUTE_FORMAT_REGEX","getVisibilityState","VISIBLE","HIDDEN","getAppId","firebaseApp","REMOTE_CONFIG_SDK_VERSION","DEFAULT_CONFIGS","FIS_AUTH_PREFIX","getConfig","performanceController","expiryString","expiry","configValid","configStringified","getStoredConfig","processConfig","installationsService","authTokenPromise","getAuthTokenPromise","getProjectId","getApiKey","Authorization","app_instance_id","app_instance_id_token","app_id","app_version","sdk_version","COULD_NOT_GET_CONFIG_MSG","storeConfig","fpr_enabled","fpr_log_source","fpr_log_endpoint_url","fpr_log_transport_key","fpr_vc_network_request_sampling_rate","fpr_vc_trace_sampling_rate","shouldLogAfterSampling","samplingRate","initializationStatus","getInitializationPromise","getDocumentReadyComplete","iidPromise","iidVal","getIidPromise","changeInitializationStatus","DEFAULT_SEND_INTERVAL_MS","DEFAULT_REMAINING_TRIES","MAX_EVENT_COUNT_PER_REQUEST","remainingTries","isTransportSetup","processQueue","timeOffset","staged","log_event","eventTime","request_time_ms","client_info","client_type","js_client_info","log_source","flTransportFullUrl","postToFlEndpoint","transportWait","nextRequestWaitMillis","requestOffset","logResponseDetails","responseAction","sendEventsToFl","dispatchQueueEvents","transportHandler","addToQueue","sendLog","resourceType","logTrace","trace","settingsService","isAuto","sendTraceLog","networkRequestMetric","http_method","httpMethod","http_response_code","response_payload_bytes","responsePayloadBytes","client_start_time_us","startTimeUs","time_to_response_initiated_us","timeToResponseInitiatedUs","time_to_response_completed_us","timeToResponseCompletedUs","perfMetric","application_info","getApplicationInfo","network_request_metric","traceMetric","is_auto","duration_us","durationUs","counters","customAttributes","getAttributes","custom_attributes","trace_metric","serializeTrace","google_app_id","web_app_info","page_url","service_worker_status","visibility_state","effective_connection_type","navigatorConnection","effectiveType","getEffectiveConnectionType","application_process_state","oobMetrics","Trace","traceMeasureName","api","randomId","traceStartMark","traceStopMark","traceMeasure","calculateTraceMetrics","traceName","startTime","duration","metrics","metricName","incrementMetric","numAsInteger","putMetric","customMetricName","valueAsInteger","providedValue","getMetric","putAttribute","attr","isValidName","isValidValue","attributeName","attributeValue","getAttribute","removeAttribute","setStartTime","setDuration","perfMeasureEntries","perfMeasureEntry","createOobTrace","navigationTimings","paintTimings","firstInputDelay","route","timeOriginUs","domInteractive","domContentLoadedEventEnd","loadEventEnd","firstPaint","paintObject","firstContentfulPaint","createUserTimingTrace","createNetworkRequestEntry","performanceEntry","responseStart","responseEnd","networkRequest","networkRequestUrl","logEndpointUrl","flEndpointUrl","logNetworkRequest","transferSize","FID_WAIT_TIME_MS","setupOobResources","setupOobTraces","resources","setupNetworkRequests","measures","setupUserTimingTraces","PerformanceController","_init","perfInstance","PerformanceCompatImpl","performanceFactory","RemoteConfigAbortSignal","registration-window","registration-project-id","registration-api-key","registration-app-id","storage-delete","fetch-client-network","fetch-timeout","fetch-client-parse","fetch-status","indexed-db-unavailable","BOOLEAN_TRUTHY_VALUES","Value","_source","asString","asBoolean","getSource","remoteConfig","lastSuccessfulFetchResponse","activeConfigEtag","getLastSuccessfulFetchResponse","getActiveConfigEtag","eTag","_storageCache","setActiveConfig","setActiveConfigEtag","ensureInitialized","_initializePromise","loadFromStorage","_isInitializationComplete","fetchConfig","abortSignal","fetchTimeoutMillis","_client","cacheMaxAgeMillis","minimumFetchIntervalMillis","setLastFetchStatus","lastFetchStatus","getAllKeys","obj1","obj2","getActiveConfig","defaultConfig","allConfigs","_logger","activeConfig","ValueImpl","CachingClient","storageCache","isCachedDataFresh","lastSuccessfulFetchTimestampMillis","cacheAgeMillis","getLastSuccessfulFetchTimestampMillis","storageOperations","setLastSuccessfulFetchTimestampMillis","setLastSuccessfulFetchResponse","RestClient","firebaseInstallations","installationId","installationToken","FIREBASE_REMOTE_CONFIG_URL_BASE","Content-Encoding","If-None-Match","requestBody","language_code","fetchPromise","timeoutPromise","responseEtag","RetryingClient","attemptFetch","RemoteConfig","fetchTimeMillis","getLastFetchStatus","toFirebaseError","APP_NAMESPACE_STORE","openDbPromise","openDatabase","etag","createCompositeKey","StorageCache","lastFetchStatusPromise","lastSuccessfulFetchTimestampMillisPromise","activeConfigPromise","timestampMillis","FirebaseLogLevel","restClient","retryingClient","cachingClient","remoteConfigInstance","RemoteConfigImpl","RemoteConfigCompatImpl","fetchAndActivate","getBoolean","getNumber","getString","remoteConfigFactory"],"mappings":"wOAqBa,MAAAA,EAAY,CAIvBC,aAAa,EAIbC,YAAY,EAKZC,YAAa,qBCZFC,EAAS,SAAUC,EAAoBC,GAClD,IAAKD,EACH,MAAME,EAAeD,IAOZC,EAAiB,SAAUD,GACtC,OAAO,IAAIE,MACT,sBACER,EAAUG,YACV,6BACAG,ICnBAG,EAAoB,SAAUC,GAElC,MAAMC,EAAgB,GACtB,IAAIC,EAAI,EACR,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAAII,OAAQD,IAAK,CACnC,IAAIE,EAAIL,EAAIM,WAAWH,GACnBE,EAAI,IACNJ,EAAIC,KAAOG,GACFA,EAAI,KACbJ,EAAIC,KAAQG,GAAK,EAAK,KAGL,QAAZ,MAAJA,IACDF,EAAI,EAAIH,EAAII,QACyB,QAAZ,MAAxBJ,EAAIM,WAAWH,EAAI,KAGpBE,EAAI,QAAgB,KAAJA,IAAe,KAA6B,KAAtBL,EAAIM,aAAaH,IACvDF,EA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,GAASoa,sDE3BI,MAAAqjB,GAAa,CAExBC,SAAU,eAEVC,OAAQ,aAERC,OAAQ,aAERC,SAAU,WAEVC,MAAO,QAEPC,QAAS,eA4CEC,GAAsB,CAEjCC,aAAc,eAEdC,eAAgB,iBAEhBC,cAAe,gBAEfC,8BAA+B,gCAE/BC,wBAAyB,0BAEzBC,aAAc,gBCwShB,SAASC,KAIP,MAAO,CACLC,wCACE,2LAxQN,SAqRaC,KApRX,MAAO,CACLC,6BACE,uDACFC,iBAAgC,GAChCC,qBACE,6LAGFC,oBACE,qJAGFC,uBACE,kKAGFC,eACE,+EAEFC,oBAAmC,kCACnCC,mBAAkC,iCAClCC,4BACE,uEACFC,wBACE,wDACFC,wBACE,6GAEFZ,wCACE,0LAGFa,6BACE,+FAEFC,kCACE,wDACFC,uBACE,0DACFC,yBACE,gKAGFC,sBAAkC,+BAClCC,0BACE,mFACFC,iBAAgC,sCAChCC,yBACE,sIAEFC,iBACE,qEACFC,qBACE,sLAGFC,qBAAoC,sCACpCC,4BACE,wLAGFC,uBACE,uDACFC,gCACE,gOAIFC,uBACE,wEACFC,8BACE,4FACFC,gBAA+B,wCAC/BC,0BACE,qEACFC,kBACE,sEACFC,oBACE,kDACFC,qBACE,uEACFC,0BACE,+KAEFC,+BACE,iFACFC,yBACE,uGAEFC,0BACE,0FAEFC,sBACE,+IAEFC,sBACE,2GAEFC,iBACE,gEACFC,2BACE,oFACFC,uBACE,gPAIFC,sBACE,wCACFC,0BACE,4GAEFC,iBACE,6KAEFC,0BACE,2EACFC,oBACE,4CACFC,gBACE,4DACFC,2BACE,2FACFC,8BACE,8HAEFC,yBACE,gIAEFC,4BACE,6EACFC,uBACE,kDACFC,uBAAsC,sCACtCC,wBACE,oEACFC,2BACE,oKAGFC,mBAAkC,wCAClCC,4BACE,2CACFC,+BACE,mEACFC,uBACE,wEACFC,0BACE,uEACF1pB,cACE,iDACF2pB,8BACE,2EACFC,6BACE,yEACFC,2CACE,wJAGFC,yBACE,kGACF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