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KkE,IAAU35C,OAAOC,UAAUC,eAAegB,KAAKu0C,EAAKkE,GCGxDu0G,EAAoB","sources":["../node_modules/dom-helpers/esm/ownerDocument.js","../node_modules/@firebase/logger/src/logger.ts","../node_modules/react/jsx-runtime.js","../node_modules/dom-helpers/esm/camelize.js","../node_modules/react-bootstrap/esm/createWithBsPrefix.js","../node_modules/dom-helpers/esm/listen.js","../node_modules/react-bootstrap/esm/Row.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/prop-types/factoryWithThrowingShims.js","../node_modules/react-bootstrap/esm/CardImg.js","../node_modules/react-bootstrap/esm/CardHeaderContext.js","../node_modules/react-bootstrap/esm/CardHeader.js","../node_modules/react-bootstrap/esm/Card.js","firebaseConfig.js","../node_modules/@restart/hooks/esm/useTimeout.js","../node_modules/react-bootstrap/esm/ToastFade.js","../node_modules/react-bootstrap/esm/ToastContext.js","../node_modules/react-bootstrap/esm/ToastHeader.js","../node_modules/react-bootstrap/esm/ToastBody.js","../node_modules/react-bootstrap/esm/Toast.js","Instructions.js","../node_modules/react-dom/cjs/react-dom.production.min.js","index.js","../node_modules/dom-helpers/esm/addEventListener.js","../node_modules/prop-types/lib/ReactPropTypesSecret.js","../node_modules/react-bootstrap/esm/ToastContainer.js","Result.js","../node_modules/react-bootstrap/esm/Container.js","../node_modules/@fortawesome/fontawesome-svg-core/index.mjs","../node_modules/@fortawesome/react-fontawesome/index.es.js","../node_modules/react/cjs/react.production.min.js","../node_modules/dom-helpers/esm/transitionEnd.js","../node_modules/dom-helpers/esm/triggerEvent.js","../node_modules/react-dom/client.js","../node_modules/react-bootstrap/esm/divWithClassName.js","../node_modules/classnames/index.js","../node_modules/react/index.js","../node_modules/prop-types/index.js","../node_modules/node_modules/closure-net/firebase/bloom_blob_es2018.js","../node_modules/node_modules/closure-net/firebase/webchannel_blob_es2018.js","../node_modules/@firebase/firestore/src/auth/user.ts","../node_modules/@firebase/firestore/src/core/version.ts","../node_modules/@firebase/firestore/src/util/log.ts","../node_modules/@firebase/firestore/src/platform/browser/format_json.ts","../node_modules/@firebase/firestore/src/util/assert.ts","../node_modules/@firebase/firestore/src/util/error.ts","../node_modules/@firebase/firestore/src/util/promise.ts","../node_modules/@firebase/firestore/src/api/credentials.ts","../node_modules/@firebase/firestore/src/platform/browser/random_bytes.ts","../node_modules/@firebase/firestore/src/util/misc.ts","../node_modules/@firebase/firestore/src/lite-api/timestamp.ts","../node_modules/@firebase/firestore/src/core/snapshot_version.ts","../node_modules/@firebase/firestore/src/model/path.ts","../node_modules/@firebase/firestore/src/model/document_key.ts","../node_modules/@firebase/firestore/src/model/field_index.ts","../node_modules/@firebase/firestore/src/local/persistence_transaction.ts","../node_modules/@firebase/firestore/src/local/local_store.ts","../node_modules/@firebase/firestore/src/local/persistence_promise.ts","../node_modules/@firebase/firestore/src/local/simple_db.ts","../node_modules/@firebase/firestore/src/core/listen_sequence.ts","../node_modules/@firebase/firestore/src/util/types.ts","../node_modules/@firebase/firestore/src/local/indexeddb_sentinels.ts","../node_modules/@firebase/firestore/src/local/indexeddb_schema_legacy.ts","../node_modules/@firebase/firestore/src/util/obj.ts","../node_modules/@firebase/firestore/src/util/sorted_map.ts","../node_modules/@firebase/firestore/src/util/sorted_set.ts","../node_modules/@firebase/firestore/src/model/field_mask.ts","../node_modules/@firebase/firestore/src/util/base64_decode_error.ts","../node_modules/@firebase/firestore/src/util/byte_string.ts","../node_modules/@firebase/firestore/src/platform/browser/base64.ts","../node_modules/@firebase/firestore/src/model/normalize.ts","../node_modules/@firebase/firestore/src/model/server_timestamps.ts","../node_modules/@firebase/firestore/src/core/database_info.ts","../node_modules/@firebase/firestore/src/model/values.ts","../node_modules/@firebase/firestore/src/model/object_value.ts","../node_modules/@firebase/firestore/src/model/document.ts","../node_modules/@firebase/firestore/src/core/bound.ts","../node_modules/@firebase/firestore/src/core/order_by.ts","../node_modules/@firebase/firestore/src/core/filter.ts","../node_modules/@firebase/firestore/src/core/target.ts","../node_modules/@firebase/firestore/src/core/query.ts","../node_modules/@firebase/firestore/src/util/obj_map.ts","../node_modules/@firebase/firestore/src/model/collections.ts","../node_modules/@firebase/firestore/src/remote/number_serializer.ts","../node_modules/@firebase/firestore/src/model/transform_operation.ts","../node_modules/@firebase/firestore/src/model/mutation.ts","../node_modules/@firebase/firestore/src/model/mutation_batch.ts","../node_modules/@firebase/firestore/src/model/overlay.ts","../node_modules/@firebase/firestore/src/remote/existence_filter.ts","../node_modules/@firebase/firestore/src/remote/rpc_error.ts","../node_modules/@firebase/firestore/src/util/testing_hooks_spi.ts","../node_modules/@firebase/firestore/src/platform/browser/text_serializer.ts","../node_modules/@firebase/firestore/src/remote/bloom_filter.ts","../node_modules/@firebase/firestore/src/remote/remote_event.ts","../node_modules/@firebase/firestore/src/remote/watch_change.ts","../node_modules/@firebase/firestore/src/remote/serializer.ts","../node_modules/@firebase/firestore/src/local/target_data.ts","../node_modules/@firebase/firestore/src/local/local_serializer.ts","../node_modules/@firebase/firestore/src/index/firestore_index_value_writer.ts","../node_modules/@firebase/firestore/src/local/memory_index_manager.ts","../node_modules/@firebase/firestore/src/local/indexeddb_index_manager.ts","../node_modules/@firebase/firestore/src/local/lru_garbage_collector.ts","../node_modules/@firebase/firestore/src/core/target_id_generator.ts","../node_modules/@firebase/firestore/src/local/remote_document_change_buffer.ts","../node_modules/@firebase/firestore/src/local/overlayed_document.ts","../node_modules/@firebase/firestore/src/local/local_documents_view.ts","../node_modules/@firebase/firestore/src/local/memory_bundle_cache.ts","../node_modules/@firebase/firestore/src/local/memory_document_overlay_cache.ts","../node_modules/@firebase/firestore/src/local/memory_globals_cache.ts","../node_modules/@firebase/firestore/src/local/reference_set.ts","../node_modules/@firebase/firestore/src/local/memory_mutation_queue.ts","../node_modules/@firebase/firestore/src/local/memory_remote_document_cache.ts","../node_modules/@firebase/firestore/src/local/memory_target_cache.ts","../node_modules/@firebase/firestore/src/local/memory_persistence.ts","../node_modules/@firebase/firestore/src/local/local_view_changes.ts","../node_modules/@firebase/firestore/src/local/query_context.ts","../node_modules/@firebase/firestore/src/local/query_engine.ts","../node_modules/@firebase/firestore/src/local/local_store_impl.ts","../node_modules/@firebase/firestore/src/local/shared_client_state.ts","../node_modules/@firebase/firestore/src/remote/connectivity_monitor_noop.ts","../node_modules/@firebase/firestore/src/platform/browser/connectivity_monitor.ts","../node_modules/@firebase/firestore/src/util/debug_uid.ts","../node_modules/@firebase/firestore/src/remote/rest_connection.ts","../node_modules/@firebase/firestore/src/remote/stream_bridge.ts","../node_modules/@firebase/firestore/src/platform/browser/webchannel_connection.ts","../node_modules/@firebase/firestore/src/platform/browser/dom.ts","../node_modules/@firebase/firestore/src/platform/browser/serializer.ts","../node_modules/@firebase/firestore/src/remote/backoff.ts","../node_modules/@firebase/firestore/src/remote/persistent_stream.ts","../node_modules/@firebase/firestore/src/remote/datastore.ts","../node_modules/@firebase/firestore/src/remote/online_state_tracker.ts","../node_modules/@firebase/firestore/src/remote/remote_store.ts","../node_modules/@firebase/firestore/src/util/async_queue.ts","../node_modules/@firebase/firestore/src/model/document_set.ts","../node_modules/@firebase/firestore/src/core/view_snapshot.ts","../node_modules/@firebase/firestore/src/core/event_manager.ts","../node_modules/@firebase/firestore/src/core/view.ts","../node_modules/@firebase/firestore/src/core/sync_engine_impl.ts","../node_modules/@firebase/firestore/src/core/component_provider.ts","../node_modules/@firebase/firestore/src/platform/browser/connection.ts","../node_modules/@firebase/firestore/src/util/async_observer.ts","../node_modules/@firebase/firestore/src/core/firestore_client.ts","../node_modules/@firebase/firestore/src/api/long_polling_options.ts","../node_modules/@firebase/firestore/src/lite-api/components.ts","../node_modules/@firebase/firestore/src/util/input_validation.ts","../node_modules/@firebase/firestore/src/lite-api/settings.ts","../node_modules/@firebase/firestore/src/local/lru_garbage_collector_impl.ts","../node_modules/@firebase/firestore/src/lite-api/database.ts","../node_modules/@firebase/firestore/src/lite-api/reference.ts","../node_modules/@firebase/firestore/src/util/async_queue_impl.ts","../node_modules/@firebase/firestore/src/api/database.ts","../node_modules/@firebase/firestore/src/lite-api/bytes.ts","../node_modules/@firebase/firestore/src/lite-api/field_path.ts","../node_modules/@firebase/firestore/src/lite-api/field_value.ts","../node_modules/@firebase/firestore/src/lite-api/geo_point.ts","../node_modules/@firebase/firestore/src/lite-api/vector_value.ts","../node_modules/@firebase/firestore/src/util/array.ts","../node_modules/@firebase/firestore/src/lite-api/user_data_reader.ts","../node_modules/@firebase/firestore/src/lite-api/snapshot.ts","../node_modules/@firebase/firestore/src/lite-api/query.ts","../node_modules/@firebase/firestore/src/lite-api/user_data_writer.ts","../node_modules/@firebase/firestore/src/api/snapshot.ts","../node_modules/@firebase/firestore/src/api/reference_impl.ts","../node_modules/@firebase/firestore/src/api/persistent_cache_index_manager.ts","../node_modules/@firebase/firestore/src/register.ts","../node_modules/@firebase/firestore/src/index.ts","../node_modules/react-bootstrap/esm/CloseButton.js","../node_modules/react-bootstrap/esm/transitionEndListener.js","../node_modules/react-bootstrap/esm/TransitionWrapper.js","../node_modules/react-bootstrap/esm/safeFindDOMNode.js","../node_modules/react-bootstrap/esm/Fade.js","../node_modules/react-bootstrap/esm/triggerBrowserReflow.js","../node_modules/@restart/hooks/esm/useCommittedRef.js","../node_modules/@restart/hooks/esm/useEventCallback.js","../node_modules/@restart/hooks/esm/useMounted.js","Footer.js","../node_modules/firebase/app/index.ts","../node_modules/idb/build/wrap-idb-value.js","../node_modules/idb/build/index.js","../node_modules/@firebase/app/src/platformLoggerService.ts","../node_modules/@firebase/app/src/logger.ts","../node_modules/@firebase/app/src/constants.ts","../node_modules/@firebase/app/src/internal.ts","../node_modules/@firebase/app/src/errors.ts","../node_modules/@firebase/app/src/firebaseApp.ts","../node_modules/@firebase/app/src/api.ts","../node_modules/@firebase/app/src/indexeddb.ts","../node_modules/@firebase/app/src/heartbeatService.ts","../node_modules/@firebase/app/src/registerCoreComponents.ts","../node_modules/@firebase/app/src/index.ts","../node_modules/dom-helpers/esm/scrollbarSize.js","../node_modules/dom-helpers/esm/activeElement.js","../node_modules/dom-helpers/esm/contains.js","../node_modules/@restart/ui/esm/ModalManager.js","../node_modules/@restart/ui/esm/DataKey.js","../node_modules/@restart/ui/esm/getScrollbarWidth.js","../node_modules/@restart/ui/esm/useWindow.js","../node_modules/@restart/ui/esm/useWaitForDOMRef.js","../node_modules/@restart/hooks/esm/useIsomorphicEffect.js","../node_modules/@restart/ui/esm/NoopTransition.js","../node_modules/@restart/ui/esm/ImperativeTransition.js","../node_modules/@restart/ui/esm/Modal.js","../node_modules/@restart/hooks/esm/usePrevious.js","../node_modules/@restart/ui/esm/utils.js","../node_modules/dom-helpers/esm/querySelectorAll.js","../node_modules/dom-helpers/esm/removeClass.js","../node_modules/react-bootstrap/esm/BootstrapModalManager.js","../node_modules/dom-helpers/esm/addClass.js","../node_modules/dom-helpers/esm/hasClass.js","../node_modules/react-bootstrap/esm/ModalBody.js","../node_modules/react-bootstrap/esm/ModalContext.js","../node_modules/react-bootstrap/esm/ModalDialog.js","../node_modules/react-bootstrap/esm/ModalFooter.js","../node_modules/react-bootstrap/esm/AbstractModalHeader.js","../node_modules/react-bootstrap/esm/ModalHeader.js","../node_modules/react-bootstrap/esm/ModalTitle.js","../node_modules/react-bootstrap/esm/Modal.js","../node_modules/@restart/hooks/esm/useCallbackRef.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/@firebase/util/src/constants.ts","../node_modules/@firebase/util/src/crypt.ts","../node_modules/@firebase/util/src/defaults.ts","../node_modules/@firebase/util/src/global.ts","../node_modules/@firebase/util/src/deferred.ts","../node_modules/@firebase/util/src/emulator.ts","../node_modules/@firebase/util/src/environment.ts","../node_modules/@firebase/util/src/errors.ts","../node_modules/@firebase/util/src/obj.ts","../node_modules/@firebase/util/src/query.ts","../node_modules/@firebase/util/src/subscribe.ts","../node_modules/@firebase/util/src/compat.ts","../node_modules/react-bootstrap/esm/ThemeProvider.js","../node_modules/@fortawesome/free-solid-svg-icons/index.mjs","../node_modules/react-dom/index.js","Rabta.js","../node_modules/dom-helpers/esm/removeEventListener.js","../node_modules/dom-helpers/esm/canUseDOM.js","../node_modules/@restart/hooks/esm/useMergedRefs.js","../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../node_modules/react-transition-group/esm/config.js","../node_modules/react-transition-group/esm/TransitionGroupContext.js","../node_modules/react-transition-group/esm/utils/reflow.js","../node_modules/react-transition-group/esm/Transition.js","../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../node_modules/react-bootstrap/esm/Col.js","../node_modules/dom-helpers/esm/getComputedStyle.js","../node_modules/dom-helpers/esm/ownerWindow.js","../node_modules/dom-helpers/esm/hyphenate.js","../node_modules/dom-helpers/esm/hyphenateStyle.js","../node_modules/dom-helpers/esm/isTransform.js","../node_modules/dom-helpers/esm/css.js","../node_modules/@firebase/component/src/component.ts","../node_modules/@firebase/component/src/constants.ts","../node_modules/@firebase/component/src/provider.ts","../node_modules/@firebase/component/src/component_container.ts","../node_modules/scheduler/index.js","../node_modules/@restart/hooks/esm/useWillUnmount.js","../node_modules/@restart/hooks/esm/useUpdatedRef.js","data.js","../node_modules/tslib/tslib.es6.mjs","../node_modules/firebase/node_modules/@firebase/auth/src/core/errors.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/log.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/assert.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/location.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/delay.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/navigator.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/emulator.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/fetch_provider.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/errors.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/index.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/authentication/recaptcha.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/account_management/account.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/time.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/id_token_result.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/invalidation.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/proactive_refresh.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/user_metadata.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/reload.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/token_manager.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/authentication/token.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/user_impl.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/instantiator.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/persistence/in_memory.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/persistence/persistence_user_manager.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/browser.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/version.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/auth/middleware.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/auth/password_policy_impl.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/auth/auth_impl.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/password_policy/get_password_policy.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/load_js.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/auth/emulator.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/credentials/auth_credential.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/account_management/email_and_password.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/authentication/email_and_password.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/credentials/email.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/authentication/email_link.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/authentication/idp.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/credentials/oauth.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/authentication/sms.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/credentials/phone.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/action_code_url.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/providers/email.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/providers/federated.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/providers/oauth.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/providers/facebook.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/providers/google.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/providers/github.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/providers/twitter.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/authentication/sign_up.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/user_credential_impl.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/strategies/anonymous.ts","../node_modules/firebase/node_modules/@firebase/auth/src/mfa/mfa_error.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/link_unlink.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/user/reauthenticate.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/strategies/credential.ts","../node_modules/firebase/node_modules/@firebase/auth/src/mfa/mfa_user.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/persistence/index.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/persistence/browser.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/persistence/local_storage.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/persistence/session_storage.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/messagechannel/receiver.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/messagechannel/promise.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/event_id.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/messagechannel/sender.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/auth_window.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/util/worker.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/persistence/indexed_db.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_loader.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_verifier.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/strategies/phone.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/account_management/mfa.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/authentication/mfa.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/providers/phone.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/resolver.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/strategies/idp.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/strategies/abstract_popup_redirect_operation.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/strategies/popup.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/strategies/redirect.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/strategies/redirect.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/auth/auth_event_manager.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/validate_origin.ts","../node_modules/firebase/node_modules/@firebase/auth/src/api/project_config/get_project_config.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/iframe/gapi.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/iframe/iframe.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/util/popup.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/util/handler.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/popup_redirect.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/auth/firebase_internal.ts","../node_modules/firebase/node_modules/@firebase/auth/src/platform_browser/index.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/auth/initialize.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/index.ts","../node_modules/firebase/node_modules/@firebase/auth/src/core/auth/register.ts","../webpack/bootstrap","../webpack/runtime/async module","../webpack/runtime/compat get default export","../webpack/runtime/define property getters","../webpack/runtime/global","../webpack/runtime/hasOwnProperty shorthand","../webpack/startup"],"sourcesContent":["/**\n * Returns the owner document of a given element.\n * \n * @param node the element\n */\nexport default function ownerDocument(node) {\n return node && node.ownerDocument || document;\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","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","var rHyphen = /-(.)/g;\nexport default function camelize(string) {\n return string.replace(rHyphen, function (_, chr) {\n return chr.toUpperCase();\n });\n}","import classNames from 'classnames';\nimport camelize from 'dom-helpers/camelize';\nimport * as React from 'react';\nimport { useBootstrapPrefix } from './ThemeProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst pascalCase = str => str[0].toUpperCase() + camelize(str).slice(1);\n// TODO: emstricten & fix the typing here! `createWithBsPrefix...`\nexport default function createWithBsPrefix(prefix, {\n displayName = pascalCase(prefix),\n Component,\n defaultProps\n} = {}) {\n const BsComponent = /*#__PURE__*/React.forwardRef(({\n className,\n bsPrefix,\n as: Tag = Component || 'div',\n ...props\n }, ref) => {\n const componentProps = {\n ...defaultProps,\n ...props\n };\n const resolvedPrefix = useBootstrapPrefix(bsPrefix, prefix);\n return /*#__PURE__*/_jsx(Tag, {\n ref: ref,\n className: classNames(className, resolvedPrefix),\n ...componentProps\n });\n });\n BsComponent.displayName = displayName;\n return BsComponent;\n}","import addEventListener from './addEventListener';\nimport removeEventListener from './removeEventListener';\n\nfunction listen(node, eventName, handler, options) {\n addEventListener(node, eventName, handler, options);\n return function () {\n removeEventListener(node, eventName, handler, options);\n };\n}\n\nexport default listen;","import classNames from 'classnames';\nimport * as React from 'react';\nimport { useBootstrapPrefix, useBootstrapBreakpoints, useBootstrapMinBreakpoint } from './ThemeProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst Row = /*#__PURE__*/React.forwardRef(({\n bsPrefix,\n className,\n // Need to define the default \"as\" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595\n as: Component = 'div',\n ...props\n}, ref) => {\n const decoratedBsPrefix = useBootstrapPrefix(bsPrefix, 'row');\n const breakpoints = useBootstrapBreakpoints();\n const minBreakpoint = useBootstrapMinBreakpoint();\n const sizePrefix = `${decoratedBsPrefix}-cols`;\n const classes = [];\n breakpoints.forEach(brkPoint => {\n const propValue = props[brkPoint];\n delete props[brkPoint];\n let cols;\n if (propValue != null && typeof propValue === 'object') {\n ({\n cols\n } = propValue);\n } else {\n cols = propValue;\n }\n const infix = brkPoint !== minBreakpoint ? `-${brkPoint}` : '';\n if (cols != null) classes.push(`${sizePrefix}${infix}-${cols}`);\n });\n return /*#__PURE__*/_jsx(Component, {\n ref: ref,\n ...props,\n className: classNames(className, decoratedBsPrefix, ...classes)\n });\n});\nRow.displayName = 'Row';\nexport default Row;","/**\n * @license React\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f=require(\"react\"),k=Symbol.for(\"react.element\"),l=Symbol.for(\"react.fragment\"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=\"\"+g);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l;exports.jsx=q;exports.jsxs=q;\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","import classNames from 'classnames';\nimport * as React from 'react';\nimport { useBootstrapPrefix } from './ThemeProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst CardImg = /*#__PURE__*/React.forwardRef(\n// Need to define the default \"as\" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595\n({\n bsPrefix,\n className,\n variant,\n as: Component = 'img',\n ...props\n}, ref) => {\n const prefix = useBootstrapPrefix(bsPrefix, 'card-img');\n return /*#__PURE__*/_jsx(Component, {\n ref: ref,\n className: classNames(variant ? `${prefix}-${variant}` : prefix, className),\n ...props\n });\n});\nCardImg.displayName = 'CardImg';\nexport default CardImg;","import * as React from 'react';\nconst context = /*#__PURE__*/React.createContext(null);\ncontext.displayName = 'CardHeaderContext';\nexport default context;","import classNames from 'classnames';\nimport * as React from 'react';\nimport { useMemo } from 'react';\nimport { useBootstrapPrefix } from './ThemeProvider';\nimport CardHeaderContext from './CardHeaderContext';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst CardHeader = /*#__PURE__*/React.forwardRef(({\n bsPrefix,\n className,\n // Need to define the default \"as\" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595\n as: Component = 'div',\n ...props\n}, ref) => {\n const prefix = useBootstrapPrefix(bsPrefix, 'card-header');\n const contextValue = useMemo(() => ({\n cardHeaderBsPrefix: prefix\n }), [prefix]);\n return /*#__PURE__*/_jsx(CardHeaderContext.Provider, {\n value: contextValue,\n children: /*#__PURE__*/_jsx(Component, {\n ref: ref,\n ...props,\n className: classNames(className, prefix)\n })\n });\n});\nCardHeader.displayName = 'CardHeader';\nexport default CardHeader;","import classNames from 'classnames';\nimport * as React from 'react';\nimport { useBootstrapPrefix } from './ThemeProvider';\nimport createWithBsPrefix from './createWithBsPrefix';\nimport divWithClassName from './divWithClassName';\nimport CardImg from './CardImg';\nimport CardHeader from './CardHeader';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst DivStyledAsH5 = divWithClassName('h5');\nconst DivStyledAsH6 = divWithClassName('h6');\nconst CardBody = createWithBsPrefix('card-body');\nconst CardTitle = createWithBsPrefix('card-title', {\n Component: DivStyledAsH5\n});\nconst CardSubtitle = createWithBsPrefix('card-subtitle', {\n Component: DivStyledAsH6\n});\nconst CardLink = createWithBsPrefix('card-link', {\n Component: 'a'\n});\nconst CardText = createWithBsPrefix('card-text', {\n Component: 'p'\n});\nconst CardFooter = createWithBsPrefix('card-footer');\nconst CardImgOverlay = createWithBsPrefix('card-img-overlay');\nconst Card = /*#__PURE__*/React.forwardRef(({\n bsPrefix,\n className,\n bg,\n text,\n border,\n body = false,\n children,\n // Need to define the default \"as\" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595\n as: Component = 'div',\n ...props\n}, ref) => {\n const prefix = useBootstrapPrefix(bsPrefix, 'card');\n return /*#__PURE__*/_jsx(Component, {\n ref: ref,\n ...props,\n className: classNames(className, prefix, bg && `bg-${bg}`, text && `text-${text}`, border && `border-${border}`),\n children: body ? /*#__PURE__*/_jsx(CardBody, {\n children: children\n }) : children\n });\n});\nCard.displayName = 'Card';\nexport default Object.assign(Card, {\n Img: CardImg,\n Title: CardTitle,\n Subtitle: CardSubtitle,\n Body: CardBody,\n Link: CardLink,\n Text: CardText,\n Header: CardHeader,\n Footer: CardFooter,\n ImgOverlay: CardImgOverlay\n});","const firebaseConfig = {\n apiKey: \"AIzaSyAC494g2ZpnaoYpMlqxIJ65D-DV70EosR4\",\n authDomain: \"rabta-398704.firebaseapp.com\",\n projectId: \"rabta-398704\",\n storageBucket: \"rabta-398704.appspot.com\",\n messagingSenderId: \"594448632180\",\n appId: \"1:594448632180:web:bc3a2e17395a5c5e07c421\",\n measurementId: \"G-BDYMR1XJ8K\",\n};\n\nexport default firebaseConfig;\n","import { useMemo, useRef } from 'react';\nimport useMounted from './useMounted';\nimport useWillUnmount from './useWillUnmount';\n\n/*\n * Browsers including Internet Explorer, Chrome, Safari, and Firefox store the\n * delay as a 32-bit signed integer internally. This causes an integer overflow\n * when using delays larger than 2,147,483,647 ms (about 24.8 days),\n * resulting in the timeout being executed immediately.\n *\n * via: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout\n */\nconst MAX_DELAY_MS = 2 ** 31 - 1;\nfunction setChainedTimeout(handleRef, fn, timeoutAtMs) {\n const delayMs = timeoutAtMs - Date.now();\n handleRef.current = delayMs <= MAX_DELAY_MS ? setTimeout(fn, delayMs) : setTimeout(() => setChainedTimeout(handleRef, fn, timeoutAtMs), MAX_DELAY_MS);\n}\n\n/**\n * Returns a controller object for setting a timeout that is properly cleaned up\n * once the component unmounts. New timeouts cancel and replace existing ones.\n *\n *\n *\n * ```tsx\n * const { set, clear } = useTimeout();\n * const [hello, showHello] = useState(false);\n * //Display hello after 5 seconds\n * set(() => showHello(true), 5000);\n * return (\n *
\n * {hello ?

Hello

: null}\n *
\n * );\n * ```\n */\nexport default function useTimeout() {\n const isMounted = useMounted();\n\n // types are confused between node and web here IDK\n const handleRef = useRef();\n useWillUnmount(() => clearTimeout(handleRef.current));\n return useMemo(() => {\n const clear = () => clearTimeout(handleRef.current);\n function set(fn, delayMs = 0) {\n if (!isMounted()) return;\n clear();\n if (delayMs <= MAX_DELAY_MS) {\n // For simplicity, if the timeout is short, just set a normal timeout.\n handleRef.current = setTimeout(fn, delayMs);\n } else {\n setChainedTimeout(handleRef, fn, Date.now() + delayMs);\n }\n }\n return {\n set,\n clear\n };\n }, []);\n}","import * as React from 'react';\nimport { ENTERING, EXITING } from 'react-transition-group/Transition';\nimport Fade from './Fade';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst fadeStyles = {\n [ENTERING]: 'showing',\n [EXITING]: 'showing show'\n};\nconst ToastFade = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/_jsx(Fade, {\n ...props,\n ref: ref,\n transitionClasses: fadeStyles\n}));\nToastFade.displayName = 'ToastFade';\nexport default ToastFade;","import * as React from 'react';\nconst ToastContext = /*#__PURE__*/React.createContext({\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onClose() {}\n});\nexport default ToastContext;","import classNames from 'classnames';\nimport * as React from 'react';\nimport { useContext } from 'react';\nimport useEventCallback from '@restart/hooks/useEventCallback';\nimport { useBootstrapPrefix } from './ThemeProvider';\nimport CloseButton from './CloseButton';\nimport ToastContext from './ToastContext';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\nconst ToastHeader = /*#__PURE__*/React.forwardRef(({\n bsPrefix,\n closeLabel = 'Close',\n closeVariant,\n closeButton = true,\n className,\n children,\n ...props\n}, ref) => {\n bsPrefix = useBootstrapPrefix(bsPrefix, 'toast-header');\n const context = useContext(ToastContext);\n const handleClick = useEventCallback(e => {\n context == null ? void 0 : context.onClose == null ? void 0 : context.onClose(e);\n });\n return /*#__PURE__*/_jsxs(\"div\", {\n ref: ref,\n ...props,\n className: classNames(bsPrefix, className),\n children: [children, closeButton && /*#__PURE__*/_jsx(CloseButton, {\n \"aria-label\": closeLabel,\n variant: closeVariant,\n onClick: handleClick,\n \"data-dismiss\": \"toast\"\n })]\n });\n});\nToastHeader.displayName = 'ToastHeader';\nexport default ToastHeader;","import createWithBsPrefix from './createWithBsPrefix';\nexport default createWithBsPrefix('toast-body');","import * as React from 'react';\nimport { useEffect, useMemo, useRef, useCallback } from 'react';\nimport classNames from 'classnames';\nimport useTimeout from '@restart/hooks/useTimeout';\nimport ToastFade from './ToastFade';\nimport ToastHeader from './ToastHeader';\nimport ToastBody from './ToastBody';\nimport { useBootstrapPrefix } from './ThemeProvider';\nimport ToastContext from './ToastContext';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst Toast = /*#__PURE__*/React.forwardRef(({\n bsPrefix,\n className,\n transition: Transition = ToastFade,\n show = true,\n animation = true,\n delay = 5000,\n autohide = false,\n onClose,\n bg,\n ...props\n}, ref) => {\n bsPrefix = useBootstrapPrefix(bsPrefix, 'toast');\n\n // We use refs for these, because we don't want to restart the autohide\n // timer in case these values change.\n const delayRef = useRef(delay);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n delayRef.current = delay;\n onCloseRef.current = onClose;\n }, [delay, onClose]);\n const autohideTimeout = useTimeout();\n const autohideToast = !!(autohide && show);\n const autohideFunc = useCallback(() => {\n if (autohideToast) {\n onCloseRef.current == null ? void 0 : onCloseRef.current();\n }\n }, [autohideToast]);\n useEffect(() => {\n // Only reset timer if show or autohide changes.\n autohideTimeout.set(autohideFunc, delayRef.current);\n }, [autohideTimeout, autohideFunc]);\n const toastContext = useMemo(() => ({\n onClose\n }), [onClose]);\n const hasAnimation = !!(Transition && animation);\n const toast = /*#__PURE__*/_jsx(\"div\", {\n ...props,\n ref: ref,\n className: classNames(bsPrefix, className, bg && `bg-${bg}`, !hasAnimation && (show ? 'show' : 'hide')),\n role: \"alert\",\n \"aria-live\": \"assertive\",\n \"aria-atomic\": \"true\"\n });\n return /*#__PURE__*/_jsx(ToastContext.Provider, {\n value: toastContext,\n children: hasAnimation && Transition ? /*#__PURE__*/_jsx(Transition, {\n in: show,\n unmountOnExit: true,\n children: toast\n }) : toast\n });\n});\nToast.displayName = 'Toast';\nexport default Object.assign(Toast, {\n Body: ToastBody,\n Header: ToastHeader\n});","import { Modal } from \"react-bootstrap\";\n\nconst Instructions = ({ showModal, setShowModal }) => {\n return (\n showModal && (\n \n \n ہدایات\n \n \n

چار الفاظ پر مشتمل چار گروپ بنائیں۔

\n

ہر گروپ کے الفاظ میں ربط (قدر مشترک) ہونا چاہیے

\n

آپ کے پاس چار غلطیوں کی گنجائش ہے۔

\n

ایک سے زیادہ معنی والے الفاظ کو دھیان سے کسی گروپ میں شامل کریں

مثلاً

\n

\n سونا۔ پیتل۔ لوہا۔ تانبا۔\n

\n

\n سونا۔ کھانا۔ پینا۔ چلنا۔\n

\n
\n \n \n \n
\n )\n );\n};\n\nexport default Instructions;\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}\nfunction Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);\nfunction Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[];\nfunction Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}\nfunction Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}\nfunction ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}\nfunction Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,\n4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=\nci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,\nf,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Uh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),\nnull;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;\nfunction Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}\nfunction Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}\nfunction Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}\nfunction ak(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;\nZj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}\nfunction ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;\nWk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\nhj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}\nfunction al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction $k(a){if(\"function\"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction yh(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)bj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3\n \n \n);","/* eslint-disable no-return-assign */\nimport canUseDOM from './canUseDOM';\nexport var optionsSupported = false;\nexport var onceSupported = false;\n\ntry {\n var options = {\n get passive() {\n return optionsSupported = true;\n },\n\n get once() {\n // eslint-disable-next-line no-multi-assign\n return onceSupported = optionsSupported = true;\n }\n\n };\n\n if (canUseDOM) {\n window.addEventListener('test', options, options);\n window.removeEventListener('test', options, true);\n }\n} catch (e) {\n /* */\n}\n\n/**\n * An `addEventListener` ponyfill, supports the `once` option\n * \n * @param node the element\n * @param eventName the event name\n * @param handle the handler\n * @param options event options\n */\nfunction addEventListener(node, eventName, handler, options) {\n if (options && typeof options !== 'boolean' && !onceSupported) {\n var once = options.once,\n capture = options.capture;\n var wrappedHandler = handler;\n\n if (!onceSupported && once) {\n wrappedHandler = handler.__once || function onceHandler(event) {\n this.removeEventListener(eventName, onceHandler, capture);\n handler.call(this, event);\n };\n\n handler.__once = wrappedHandler;\n }\n\n node.addEventListener(eventName, wrappedHandler, optionsSupported ? options : capture);\n }\n\n node.addEventListener(eventName, handler, options);\n}\n\nexport default addEventListener;","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","import classNames from 'classnames';\nimport * as React from 'react';\nimport { useBootstrapPrefix } from './ThemeProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst positionClasses = {\n 'top-start': 'top-0 start-0',\n 'top-center': 'top-0 start-50 translate-middle-x',\n 'top-end': 'top-0 end-0',\n 'middle-start': 'top-50 start-0 translate-middle-y',\n 'middle-center': 'top-50 start-50 translate-middle',\n 'middle-end': 'top-50 end-0 translate-middle-y',\n 'bottom-start': 'bottom-0 start-0',\n 'bottom-center': 'bottom-0 start-50 translate-middle-x',\n 'bottom-end': 'bottom-0 end-0'\n};\nconst ToastContainer = /*#__PURE__*/React.forwardRef(({\n bsPrefix,\n position,\n containerPosition,\n className,\n // Need to define the default \"as\" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595\n as: Component = 'div',\n ...props\n}, ref) => {\n bsPrefix = useBootstrapPrefix(bsPrefix, 'toast-container');\n return /*#__PURE__*/_jsx(Component, {\n ref: ref,\n ...props,\n className: classNames(bsPrefix, position && positionClasses[position], containerPosition && `position-${containerPosition}`, className)\n });\n});\nToastContainer.displayName = 'ToastContainer';\nexport default ToastContainer;","import React from \"react\";\nimport { Modal, Container, Row, Col, Card, ToastContainer, Toast } from \"react-bootstrap\";\n\nconst Result = ({\n showResults,\n designedBy,\n lost,\n tries,\n attempts,\n timeLeft,\n shareResults,\n clipboard,\n setClipboard,\n setShowResults,\n}) =>\n showResults && (\n \n \n Game Over - puzzle by {designedBy}\n \n \n {lost &&

Next time!

}\n {!lost &&

{`Won with ${tries} tries remaining!`}

}\n \n {attempts.map((attempt, index) => (\n \n {attempt.map((item, index) => (\n \n \n \n ))}\n \n ))}\n \n

Next Rabta in {timeLeft}

\n \n {clipboard && (\n \n setClipboard(false)}\n autohide\n show={clipboard}\n className=\"bg-secondary text-white\">\n Results are copied to clipboard\n \n \n )}\n
\n \n \n \n
\n );\n\nexport default Result;\n","import classNames from 'classnames';\nimport * as React from 'react';\nimport { useBootstrapPrefix } from './ThemeProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst Container = /*#__PURE__*/React.forwardRef(({\n bsPrefix,\n fluid = false,\n // Need to define the default \"as\" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595\n as: Component = 'div',\n className,\n ...props\n}, ref) => {\n const prefix = useBootstrapPrefix(bsPrefix, 'container');\n const suffix = typeof fluid === 'string' ? `-${fluid}` : '-fluid';\n return /*#__PURE__*/_jsx(Component, {\n ref: ref,\n ...props,\n className: classNames(className, fluid ? `${prefix}${suffix}` : prefix)\n });\n});\nContainer.displayName = 'Container';\nexport default Container;","function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n enumerableOnly && (symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n })), keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = null != arguments[i] ? arguments[i] : {};\n i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n\n return target;\n}\n\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}\n\nfunction _wrapRegExp() {\n _wrapRegExp = function (re, groups) {\n return new BabelRegExp(re, void 0, groups);\n };\n\n var _super = RegExp.prototype,\n _groups = new WeakMap();\n\n function BabelRegExp(re, flags, groups) {\n var _this = new RegExp(re, flags);\n\n return _groups.set(_this, groups || _groups.get(re)), _setPrototypeOf(_this, BabelRegExp.prototype);\n }\n\n function buildGroups(result, re) {\n var g = _groups.get(re);\n\n return Object.keys(g).reduce(function (groups, name) {\n return groups[name] = result[g[name]], groups;\n }, Object.create(null));\n }\n\n return _inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) {\n var result = _super.exec.call(this, str);\n\n return result && (result.groups = buildGroups(result, this)), result;\n }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {\n if (\"string\" == typeof substitution) {\n var groups = _groups.get(this);\n\n return _super[Symbol.replace].call(this, str, substitution.replace(/\\$<([^>]+)>/g, function (_, name) {\n return \"$\" + groups[name];\n }));\n }\n\n if (\"function\" == typeof substitution) {\n var _this = this;\n\n return _super[Symbol.replace].call(this, str, function () {\n var args = arguments;\n return \"object\" != typeof args[args.length - 1] && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args);\n });\n }\n\n return _super[Symbol.replace].call(this, str, substitution);\n }, _wrapRegExp.apply(this, arguments);\n}\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n Object.defineProperty(subClass, \"prototype\", {\n writable: false\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n}\n\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();\n}\n\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\n\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\n\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}\n\nfunction _iterableToArrayLimit(arr, i) {\n var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"];\n\n if (_i == null) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n\n var _s, _e;\n\n try {\n for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nvar noop = function noop() {};\n\nvar _WINDOW = {};\nvar _DOCUMENT = {};\nvar _MUTATION_OBSERVER = null;\nvar _PERFORMANCE = {\n mark: noop,\n measure: noop\n};\n\ntry {\n if (typeof window !== 'undefined') _WINDOW = window;\n if (typeof document !== 'undefined') _DOCUMENT = document;\n if (typeof MutationObserver !== 'undefined') _MUTATION_OBSERVER = MutationObserver;\n if (typeof performance !== 'undefined') _PERFORMANCE = performance;\n} catch (e) {}\n\nvar _ref = _WINDOW.navigator || {},\n _ref$userAgent = _ref.userAgent,\n userAgent = _ref$userAgent === void 0 ? '' : _ref$userAgent;\nvar WINDOW = _WINDOW;\nvar DOCUMENT = _DOCUMENT;\nvar MUTATION_OBSERVER = _MUTATION_OBSERVER;\nvar PERFORMANCE = _PERFORMANCE;\nvar IS_BROWSER = !!WINDOW.document;\nvar IS_DOM = !!DOCUMENT.documentElement && !!DOCUMENT.head && typeof DOCUMENT.addEventListener === 'function' && typeof DOCUMENT.createElement === 'function';\nvar IS_IE = ~userAgent.indexOf('MSIE') || ~userAgent.indexOf('Trident/');\n\nvar _familyProxy, _familyProxy2, _familyProxy3, _familyProxy4, _familyProxy5;\n\nvar NAMESPACE_IDENTIFIER = '___FONT_AWESOME___';\nvar UNITS_IN_GRID = 16;\nvar DEFAULT_CSS_PREFIX = 'fa';\nvar DEFAULT_REPLACEMENT_CLASS = 'svg-inline--fa';\nvar DATA_FA_I2SVG = 'data-fa-i2svg';\nvar DATA_FA_PSEUDO_ELEMENT = 'data-fa-pseudo-element';\nvar DATA_FA_PSEUDO_ELEMENT_PENDING = 'data-fa-pseudo-element-pending';\nvar DATA_PREFIX = 'data-prefix';\nvar DATA_ICON = 'data-icon';\nvar HTML_CLASS_I2SVG_BASE_CLASS = 'fontawesome-i2svg';\nvar MUTATION_APPROACH_ASYNC = 'async';\nvar TAGNAMES_TO_SKIP_FOR_PSEUDOELEMENTS = ['HTML', 'HEAD', 'STYLE', 'SCRIPT'];\nvar PRODUCTION = function () {\n try {\n return process.env.NODE_ENV === 'production';\n } catch (e) {\n return false;\n }\n}();\nvar FAMILY_CLASSIC = 'classic';\nvar FAMILY_SHARP = 'sharp';\nvar FAMILIES = [FAMILY_CLASSIC, FAMILY_SHARP];\n\nfunction familyProxy(obj) {\n // Defaults to the classic family if family is not available\n return new Proxy(obj, {\n get: function get(target, prop) {\n return prop in target ? target[prop] : target[FAMILY_CLASSIC];\n }\n });\n}\nvar PREFIX_TO_STYLE = familyProxy((_familyProxy = {}, _defineProperty(_familyProxy, FAMILY_CLASSIC, {\n 'fa': 'solid',\n 'fas': 'solid',\n 'fa-solid': 'solid',\n 'far': 'regular',\n 'fa-regular': 'regular',\n 'fal': 'light',\n 'fa-light': 'light',\n 'fat': 'thin',\n 'fa-thin': 'thin',\n 'fad': 'duotone',\n 'fa-duotone': 'duotone',\n 'fab': 'brands',\n 'fa-brands': 'brands',\n 'fak': 'kit',\n 'fakd': 'kit',\n 'fa-kit': 'kit',\n 'fa-kit-duotone': 'kit'\n}), _defineProperty(_familyProxy, FAMILY_SHARP, {\n 'fa': 'solid',\n 'fass': 'solid',\n 'fa-solid': 'solid',\n 'fasr': 'regular',\n 'fa-regular': 'regular',\n 'fasl': 'light',\n 'fa-light': 'light',\n 'fast': 'thin',\n 'fa-thin': 'thin'\n}), _familyProxy));\nvar STYLE_TO_PREFIX = familyProxy((_familyProxy2 = {}, _defineProperty(_familyProxy2, FAMILY_CLASSIC, {\n solid: 'fas',\n regular: 'far',\n light: 'fal',\n thin: 'fat',\n duotone: 'fad',\n brands: 'fab',\n kit: 'fak'\n}), _defineProperty(_familyProxy2, FAMILY_SHARP, {\n solid: 'fass',\n regular: 'fasr',\n light: 'fasl',\n thin: 'fast'\n}), _familyProxy2));\nvar PREFIX_TO_LONG_STYLE = familyProxy((_familyProxy3 = {}, _defineProperty(_familyProxy3, FAMILY_CLASSIC, {\n fab: 'fa-brands',\n fad: 'fa-duotone',\n fak: 'fa-kit',\n fal: 'fa-light',\n far: 'fa-regular',\n fas: 'fa-solid',\n fat: 'fa-thin'\n}), _defineProperty(_familyProxy3, FAMILY_SHARP, {\n fass: 'fa-solid',\n fasr: 'fa-regular',\n fasl: 'fa-light',\n fast: 'fa-thin'\n}), _familyProxy3));\nvar LONG_STYLE_TO_PREFIX = familyProxy((_familyProxy4 = {}, _defineProperty(_familyProxy4, FAMILY_CLASSIC, {\n 'fa-brands': 'fab',\n 'fa-duotone': 'fad',\n 'fa-kit': 'fak',\n 'fa-light': 'fal',\n 'fa-regular': 'far',\n 'fa-solid': 'fas',\n 'fa-thin': 'fat'\n}), _defineProperty(_familyProxy4, FAMILY_SHARP, {\n 'fa-solid': 'fass',\n 'fa-regular': 'fasr',\n 'fa-light': 'fasl',\n 'fa-thin': 'fast'\n}), _familyProxy4));\nvar ICON_SELECTION_SYNTAX_PATTERN = /fa(s|r|l|t|d|b|k|ss|sr|sl|st)?[\\-\\ ]/; // eslint-disable-line no-useless-escape\n\nvar LAYERS_TEXT_CLASSNAME = 'fa-layers-text';\nvar FONT_FAMILY_PATTERN = /Font ?Awesome ?([56 ]*)(Solid|Regular|Light|Thin|Duotone|Brands|Free|Pro|Sharp|Kit)?.*/i;\nvar FONT_WEIGHT_TO_PREFIX = familyProxy((_familyProxy5 = {}, _defineProperty(_familyProxy5, FAMILY_CLASSIC, {\n 900: 'fas',\n 400: 'far',\n normal: 'far',\n 300: 'fal',\n 100: 'fat'\n}), _defineProperty(_familyProxy5, FAMILY_SHARP, {\n 900: 'fass',\n 400: 'fasr',\n 300: 'fasl',\n 100: 'fast'\n}), _familyProxy5));\nvar oneToTen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\nvar oneToTwenty = oneToTen.concat([11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);\nvar ATTRIBUTES_WATCHED_FOR_MUTATION = ['class', 'data-prefix', 'data-icon', 'data-fa-transform', 'data-fa-mask'];\nvar DUOTONE_CLASSES = {\n GROUP: 'duotone-group',\n SWAP_OPACITY: 'swap-opacity',\n PRIMARY: 'primary',\n SECONDARY: 'secondary'\n};\nvar prefixes = new Set();\nObject.keys(STYLE_TO_PREFIX[FAMILY_CLASSIC]).map(prefixes.add.bind(prefixes));\nObject.keys(STYLE_TO_PREFIX[FAMILY_SHARP]).map(prefixes.add.bind(prefixes));\nvar RESERVED_CLASSES = [].concat(FAMILIES, _toConsumableArray(prefixes), ['2xs', 'xs', 'sm', 'lg', 'xl', '2xl', 'beat', 'border', 'fade', 'beat-fade', 'bounce', 'flip-both', 'flip-horizontal', 'flip-vertical', 'flip', 'fw', 'inverse', 'layers-counter', 'layers-text', 'layers', 'li', 'pull-left', 'pull-right', 'pulse', 'rotate-180', 'rotate-270', 'rotate-90', 'rotate-by', 'shake', 'spin-pulse', 'spin-reverse', 'spin', 'stack-1x', 'stack-2x', 'stack', 'ul', DUOTONE_CLASSES.GROUP, DUOTONE_CLASSES.SWAP_OPACITY, DUOTONE_CLASSES.PRIMARY, DUOTONE_CLASSES.SECONDARY]).concat(oneToTen.map(function (n) {\n return \"\".concat(n, \"x\");\n})).concat(oneToTwenty.map(function (n) {\n return \"w-\".concat(n);\n}));\n\nvar initial = WINDOW.FontAwesomeConfig || {};\n\nfunction getAttrConfig(attr) {\n var element = DOCUMENT.querySelector('script[' + attr + ']');\n\n if (element) {\n return element.getAttribute(attr);\n }\n}\n\nfunction coerce(val) {\n // Getting an empty string will occur if the attribute is set on the HTML tag but without a value\n // We'll assume that this is an indication that it should be toggled to true\n if (val === '') return true;\n if (val === 'false') return false;\n if (val === 'true') return true;\n return val;\n}\n\nif (DOCUMENT && typeof DOCUMENT.querySelector === 'function') {\n var attrs = [['data-family-prefix', 'familyPrefix'], ['data-css-prefix', 'cssPrefix'], ['data-family-default', 'familyDefault'], ['data-style-default', 'styleDefault'], ['data-replacement-class', 'replacementClass'], ['data-auto-replace-svg', 'autoReplaceSvg'], ['data-auto-add-css', 'autoAddCss'], ['data-auto-a11y', 'autoA11y'], ['data-search-pseudo-elements', 'searchPseudoElements'], ['data-observe-mutations', 'observeMutations'], ['data-mutate-approach', 'mutateApproach'], ['data-keep-original-source', 'keepOriginalSource'], ['data-measure-performance', 'measurePerformance'], ['data-show-missing-icons', 'showMissingIcons']];\n attrs.forEach(function (_ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n attr = _ref2[0],\n key = _ref2[1];\n\n var val = coerce(getAttrConfig(attr));\n\n if (val !== undefined && val !== null) {\n initial[key] = val;\n }\n });\n}\n\nvar _default = {\n styleDefault: 'solid',\n familyDefault: 'classic',\n cssPrefix: DEFAULT_CSS_PREFIX,\n replacementClass: DEFAULT_REPLACEMENT_CLASS,\n autoReplaceSvg: true,\n autoAddCss: true,\n autoA11y: true,\n searchPseudoElements: false,\n observeMutations: true,\n mutateApproach: 'async',\n keepOriginalSource: true,\n measurePerformance: false,\n showMissingIcons: true\n}; // familyPrefix is deprecated but we must still support it if present\n\nif (initial.familyPrefix) {\n initial.cssPrefix = initial.familyPrefix;\n}\n\nvar _config = _objectSpread2(_objectSpread2({}, _default), initial);\n\nif (!_config.autoReplaceSvg) _config.observeMutations = false;\nvar config = {};\nObject.keys(_default).forEach(function (key) {\n Object.defineProperty(config, key, {\n enumerable: true,\n set: function set(val) {\n _config[key] = val;\n\n _onChangeCb.forEach(function (cb) {\n return cb(config);\n });\n },\n get: function get() {\n return _config[key];\n }\n });\n}); // familyPrefix is deprecated as of 6.2.0 and should be removed in 7.0.0\n\nObject.defineProperty(config, 'familyPrefix', {\n enumerable: true,\n set: function set(val) {\n _config.cssPrefix = val;\n\n _onChangeCb.forEach(function (cb) {\n return cb(config);\n });\n },\n get: function get() {\n return _config.cssPrefix;\n }\n});\nWINDOW.FontAwesomeConfig = config;\nvar _onChangeCb = [];\nfunction onChange(cb) {\n _onChangeCb.push(cb);\n\n return function () {\n _onChangeCb.splice(_onChangeCb.indexOf(cb), 1);\n };\n}\n\nvar d = UNITS_IN_GRID;\nvar meaninglessTransform = {\n size: 16,\n x: 0,\n y: 0,\n rotate: 0,\n flipX: false,\n flipY: false\n};\nfunction insertCss(css) {\n if (!css || !IS_DOM) {\n return;\n }\n\n var style = DOCUMENT.createElement('style');\n style.setAttribute('type', 'text/css');\n style.innerHTML = css;\n var headChildren = DOCUMENT.head.childNodes;\n var beforeChild = null;\n\n for (var i = headChildren.length - 1; i > -1; i--) {\n var child = headChildren[i];\n var tagName = (child.tagName || '').toUpperCase();\n\n if (['STYLE', 'LINK'].indexOf(tagName) > -1) {\n beforeChild = child;\n }\n }\n\n DOCUMENT.head.insertBefore(style, beforeChild);\n return css;\n}\nvar idPool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\nfunction nextUniqueId() {\n var size = 12;\n var id = '';\n\n while (size-- > 0) {\n id += idPool[Math.random() * 62 | 0];\n }\n\n return id;\n}\nfunction toArray(obj) {\n var array = [];\n\n for (var i = (obj || []).length >>> 0; i--;) {\n array[i] = obj[i];\n }\n\n return array;\n}\nfunction classArray(node) {\n if (node.classList) {\n return toArray(node.classList);\n } else {\n return (node.getAttribute('class') || '').split(' ').filter(function (i) {\n return i;\n });\n }\n}\nfunction htmlEscape(str) {\n return \"\".concat(str).replace(/&/g, '&').replace(/\"/g, '"').replace(/'/g, ''').replace(//g, '>');\n}\nfunction joinAttributes(attributes) {\n return Object.keys(attributes || {}).reduce(function (acc, attributeName) {\n return acc + \"\".concat(attributeName, \"=\\\"\").concat(htmlEscape(attributes[attributeName]), \"\\\" \");\n }, '').trim();\n}\nfunction joinStyles(styles) {\n return Object.keys(styles || {}).reduce(function (acc, styleName) {\n return acc + \"\".concat(styleName, \": \").concat(styles[styleName].trim(), \";\");\n }, '');\n}\nfunction transformIsMeaningful(transform) {\n return transform.size !== meaninglessTransform.size || transform.x !== meaninglessTransform.x || transform.y !== meaninglessTransform.y || transform.rotate !== meaninglessTransform.rotate || transform.flipX || transform.flipY;\n}\nfunction transformForSvg(_ref) {\n var transform = _ref.transform,\n containerWidth = _ref.containerWidth,\n iconWidth = _ref.iconWidth;\n var outer = {\n transform: \"translate(\".concat(containerWidth / 2, \" 256)\")\n };\n var innerTranslate = \"translate(\".concat(transform.x * 32, \", \").concat(transform.y * 32, \") \");\n var innerScale = \"scale(\".concat(transform.size / 16 * (transform.flipX ? -1 : 1), \", \").concat(transform.size / 16 * (transform.flipY ? -1 : 1), \") \");\n var innerRotate = \"rotate(\".concat(transform.rotate, \" 0 0)\");\n var inner = {\n transform: \"\".concat(innerTranslate, \" \").concat(innerScale, \" \").concat(innerRotate)\n };\n var path = {\n transform: \"translate(\".concat(iconWidth / 2 * -1, \" -256)\")\n };\n return {\n outer: outer,\n inner: inner,\n path: path\n };\n}\nfunction transformForCss(_ref2) {\n var transform = _ref2.transform,\n _ref2$width = _ref2.width,\n width = _ref2$width === void 0 ? UNITS_IN_GRID : _ref2$width,\n _ref2$height = _ref2.height,\n height = _ref2$height === void 0 ? UNITS_IN_GRID : _ref2$height,\n _ref2$startCentered = _ref2.startCentered,\n startCentered = _ref2$startCentered === void 0 ? false : _ref2$startCentered;\n var val = '';\n\n if (startCentered && IS_IE) {\n val += \"translate(\".concat(transform.x / d - width / 2, \"em, \").concat(transform.y / d - height / 2, \"em) \");\n } else if (startCentered) {\n val += \"translate(calc(-50% + \".concat(transform.x / d, \"em), calc(-50% + \").concat(transform.y / d, \"em)) \");\n } else {\n val += \"translate(\".concat(transform.x / d, \"em, \").concat(transform.y / d, \"em) \");\n }\n\n val += \"scale(\".concat(transform.size / d * (transform.flipX ? -1 : 1), \", \").concat(transform.size / d * (transform.flipY ? -1 : 1), \") \");\n val += \"rotate(\".concat(transform.rotate, \"deg) \");\n return val;\n}\n\nvar baseStyles = \":root, :host {\\n --fa-font-solid: normal 900 1em/1 \\\"Font Awesome 6 Solid\\\";\\n --fa-font-regular: normal 400 1em/1 \\\"Font Awesome 6 Regular\\\";\\n --fa-font-light: normal 300 1em/1 \\\"Font Awesome 6 Light\\\";\\n --fa-font-thin: normal 100 1em/1 \\\"Font Awesome 6 Thin\\\";\\n --fa-font-duotone: normal 900 1em/1 \\\"Font Awesome 6 Duotone\\\";\\n --fa-font-sharp-solid: normal 900 1em/1 \\\"Font Awesome 6 Sharp\\\";\\n --fa-font-sharp-regular: normal 400 1em/1 \\\"Font Awesome 6 Sharp\\\";\\n --fa-font-sharp-light: normal 300 1em/1 \\\"Font Awesome 6 Sharp\\\";\\n --fa-font-sharp-thin: normal 100 1em/1 \\\"Font Awesome 6 Sharp\\\";\\n --fa-font-brands: normal 400 1em/1 \\\"Font Awesome 6 Brands\\\";\\n}\\n\\nsvg:not(:root).svg-inline--fa, svg:not(:host).svg-inline--fa {\\n overflow: visible;\\n box-sizing: content-box;\\n}\\n\\n.svg-inline--fa {\\n display: var(--fa-display, inline-block);\\n height: 1em;\\n overflow: visible;\\n vertical-align: -0.125em;\\n}\\n.svg-inline--fa.fa-2xs {\\n vertical-align: 0.1em;\\n}\\n.svg-inline--fa.fa-xs {\\n vertical-align: 0em;\\n}\\n.svg-inline--fa.fa-sm {\\n vertical-align: -0.0714285705em;\\n}\\n.svg-inline--fa.fa-lg {\\n vertical-align: -0.2em;\\n}\\n.svg-inline--fa.fa-xl {\\n vertical-align: -0.25em;\\n}\\n.svg-inline--fa.fa-2xl {\\n vertical-align: -0.3125em;\\n}\\n.svg-inline--fa.fa-pull-left {\\n margin-right: var(--fa-pull-margin, 0.3em);\\n width: auto;\\n}\\n.svg-inline--fa.fa-pull-right {\\n margin-left: var(--fa-pull-margin, 0.3em);\\n width: auto;\\n}\\n.svg-inline--fa.fa-li {\\n width: var(--fa-li-width, 2em);\\n top: 0.25em;\\n}\\n.svg-inline--fa.fa-fw {\\n width: var(--fa-fw-width, 1.25em);\\n}\\n\\n.fa-layers svg.svg-inline--fa {\\n bottom: 0;\\n left: 0;\\n margin: auto;\\n position: absolute;\\n right: 0;\\n top: 0;\\n}\\n\\n.fa-layers-counter, .fa-layers-text {\\n display: inline-block;\\n position: absolute;\\n text-align: center;\\n}\\n\\n.fa-layers {\\n display: inline-block;\\n height: 1em;\\n position: relative;\\n text-align: center;\\n vertical-align: -0.125em;\\n width: 1em;\\n}\\n.fa-layers svg.svg-inline--fa {\\n -webkit-transform-origin: center center;\\n transform-origin: center center;\\n}\\n\\n.fa-layers-text {\\n left: 50%;\\n top: 50%;\\n -webkit-transform: translate(-50%, -50%);\\n transform: translate(-50%, -50%);\\n -webkit-transform-origin: center center;\\n transform-origin: center center;\\n}\\n\\n.fa-layers-counter {\\n background-color: var(--fa-counter-background-color, #ff253a);\\n border-radius: var(--fa-counter-border-radius, 1em);\\n box-sizing: border-box;\\n color: var(--fa-inverse, #fff);\\n line-height: var(--fa-counter-line-height, 1);\\n max-width: var(--fa-counter-max-width, 5em);\\n min-width: var(--fa-counter-min-width, 1.5em);\\n overflow: hidden;\\n padding: var(--fa-counter-padding, 0.25em 0.5em);\\n right: var(--fa-right, 0);\\n text-overflow: ellipsis;\\n top: var(--fa-top, 0);\\n -webkit-transform: scale(var(--fa-counter-scale, 0.25));\\n transform: scale(var(--fa-counter-scale, 0.25));\\n -webkit-transform-origin: top right;\\n transform-origin: top right;\\n}\\n\\n.fa-layers-bottom-right {\\n bottom: var(--fa-bottom, 0);\\n right: var(--fa-right, 0);\\n top: auto;\\n -webkit-transform: scale(var(--fa-layers-scale, 0.25));\\n transform: scale(var(--fa-layers-scale, 0.25));\\n -webkit-transform-origin: bottom right;\\n transform-origin: bottom right;\\n}\\n\\n.fa-layers-bottom-left {\\n bottom: var(--fa-bottom, 0);\\n left: var(--fa-left, 0);\\n right: auto;\\n top: auto;\\n -webkit-transform: scale(var(--fa-layers-scale, 0.25));\\n transform: scale(var(--fa-layers-scale, 0.25));\\n -webkit-transform-origin: bottom left;\\n transform-origin: bottom left;\\n}\\n\\n.fa-layers-top-right {\\n top: var(--fa-top, 0);\\n right: var(--fa-right, 0);\\n -webkit-transform: scale(var(--fa-layers-scale, 0.25));\\n transform: scale(var(--fa-layers-scale, 0.25));\\n -webkit-transform-origin: top right;\\n transform-origin: top right;\\n}\\n\\n.fa-layers-top-left {\\n left: var(--fa-left, 0);\\n right: auto;\\n top: var(--fa-top, 0);\\n -webkit-transform: scale(var(--fa-layers-scale, 0.25));\\n transform: scale(var(--fa-layers-scale, 0.25));\\n -webkit-transform-origin: top left;\\n transform-origin: top left;\\n}\\n\\n.fa-1x {\\n font-size: 1em;\\n}\\n\\n.fa-2x {\\n font-size: 2em;\\n}\\n\\n.fa-3x {\\n font-size: 3em;\\n}\\n\\n.fa-4x {\\n font-size: 4em;\\n}\\n\\n.fa-5x {\\n font-size: 5em;\\n}\\n\\n.fa-6x {\\n font-size: 6em;\\n}\\n\\n.fa-7x {\\n font-size: 7em;\\n}\\n\\n.fa-8x {\\n font-size: 8em;\\n}\\n\\n.fa-9x {\\n font-size: 9em;\\n}\\n\\n.fa-10x {\\n font-size: 10em;\\n}\\n\\n.fa-2xs {\\n font-size: 0.625em;\\n line-height: 0.1em;\\n vertical-align: 0.225em;\\n}\\n\\n.fa-xs {\\n font-size: 0.75em;\\n line-height: 0.0833333337em;\\n vertical-align: 0.125em;\\n}\\n\\n.fa-sm {\\n font-size: 0.875em;\\n line-height: 0.0714285718em;\\n vertical-align: 0.0535714295em;\\n}\\n\\n.fa-lg {\\n font-size: 1.25em;\\n line-height: 0.05em;\\n vertical-align: -0.075em;\\n}\\n\\n.fa-xl {\\n font-size: 1.5em;\\n line-height: 0.0416666682em;\\n vertical-align: -0.125em;\\n}\\n\\n.fa-2xl {\\n font-size: 2em;\\n line-height: 0.03125em;\\n vertical-align: -0.1875em;\\n}\\n\\n.fa-fw {\\n text-align: center;\\n width: 1.25em;\\n}\\n\\n.fa-ul {\\n list-style-type: none;\\n margin-left: var(--fa-li-margin, 2.5em);\\n padding-left: 0;\\n}\\n.fa-ul > li {\\n position: relative;\\n}\\n\\n.fa-li {\\n left: calc(var(--fa-li-width, 2em) * -1);\\n position: absolute;\\n text-align: center;\\n width: var(--fa-li-width, 2em);\\n line-height: inherit;\\n}\\n\\n.fa-border {\\n border-color: var(--fa-border-color, #eee);\\n border-radius: var(--fa-border-radius, 0.1em);\\n border-style: var(--fa-border-style, solid);\\n border-width: var(--fa-border-width, 0.08em);\\n padding: var(--fa-border-padding, 0.2em 0.25em 0.15em);\\n}\\n\\n.fa-pull-left {\\n float: left;\\n margin-right: var(--fa-pull-margin, 0.3em);\\n}\\n\\n.fa-pull-right {\\n float: right;\\n margin-left: var(--fa-pull-margin, 0.3em);\\n}\\n\\n.fa-beat {\\n -webkit-animation-name: fa-beat;\\n animation-name: fa-beat;\\n -webkit-animation-delay: var(--fa-animation-delay, 0s);\\n animation-delay: var(--fa-animation-delay, 0s);\\n -webkit-animation-direction: var(--fa-animation-direction, normal);\\n animation-direction: var(--fa-animation-direction, normal);\\n -webkit-animation-duration: var(--fa-animation-duration, 1s);\\n animation-duration: var(--fa-animation-duration, 1s);\\n -webkit-animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n -webkit-animation-timing-function: var(--fa-animation-timing, ease-in-out);\\n animation-timing-function: var(--fa-animation-timing, ease-in-out);\\n}\\n\\n.fa-bounce {\\n -webkit-animation-name: fa-bounce;\\n animation-name: fa-bounce;\\n -webkit-animation-delay: var(--fa-animation-delay, 0s);\\n animation-delay: var(--fa-animation-delay, 0s);\\n -webkit-animation-direction: var(--fa-animation-direction, normal);\\n animation-direction: var(--fa-animation-direction, normal);\\n -webkit-animation-duration: var(--fa-animation-duration, 1s);\\n animation-duration: var(--fa-animation-duration, 1s);\\n -webkit-animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n -webkit-animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.28, 0.84, 0.42, 1));\\n animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.28, 0.84, 0.42, 1));\\n}\\n\\n.fa-fade {\\n -webkit-animation-name: fa-fade;\\n animation-name: fa-fade;\\n -webkit-animation-delay: var(--fa-animation-delay, 0s);\\n animation-delay: var(--fa-animation-delay, 0s);\\n -webkit-animation-direction: var(--fa-animation-direction, normal);\\n animation-direction: var(--fa-animation-direction, normal);\\n -webkit-animation-duration: var(--fa-animation-duration, 1s);\\n animation-duration: var(--fa-animation-duration, 1s);\\n -webkit-animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n -webkit-animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.4, 0, 0.6, 1));\\n animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.4, 0, 0.6, 1));\\n}\\n\\n.fa-beat-fade {\\n -webkit-animation-name: fa-beat-fade;\\n animation-name: fa-beat-fade;\\n -webkit-animation-delay: var(--fa-animation-delay, 0s);\\n animation-delay: var(--fa-animation-delay, 0s);\\n -webkit-animation-direction: var(--fa-animation-direction, normal);\\n animation-direction: var(--fa-animation-direction, normal);\\n -webkit-animation-duration: var(--fa-animation-duration, 1s);\\n animation-duration: var(--fa-animation-duration, 1s);\\n -webkit-animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n -webkit-animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.4, 0, 0.6, 1));\\n animation-timing-function: var(--fa-animation-timing, cubic-bezier(0.4, 0, 0.6, 1));\\n}\\n\\n.fa-flip {\\n -webkit-animation-name: fa-flip;\\n animation-name: fa-flip;\\n -webkit-animation-delay: var(--fa-animation-delay, 0s);\\n animation-delay: var(--fa-animation-delay, 0s);\\n -webkit-animation-direction: var(--fa-animation-direction, normal);\\n animation-direction: var(--fa-animation-direction, normal);\\n -webkit-animation-duration: var(--fa-animation-duration, 1s);\\n animation-duration: var(--fa-animation-duration, 1s);\\n -webkit-animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n -webkit-animation-timing-function: var(--fa-animation-timing, ease-in-out);\\n animation-timing-function: var(--fa-animation-timing, ease-in-out);\\n}\\n\\n.fa-shake {\\n -webkit-animation-name: fa-shake;\\n animation-name: fa-shake;\\n -webkit-animation-delay: var(--fa-animation-delay, 0s);\\n animation-delay: var(--fa-animation-delay, 0s);\\n -webkit-animation-direction: var(--fa-animation-direction, normal);\\n animation-direction: var(--fa-animation-direction, normal);\\n -webkit-animation-duration: var(--fa-animation-duration, 1s);\\n animation-duration: var(--fa-animation-duration, 1s);\\n -webkit-animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n -webkit-animation-timing-function: var(--fa-animation-timing, linear);\\n animation-timing-function: var(--fa-animation-timing, linear);\\n}\\n\\n.fa-spin {\\n -webkit-animation-name: fa-spin;\\n animation-name: fa-spin;\\n -webkit-animation-delay: var(--fa-animation-delay, 0s);\\n animation-delay: var(--fa-animation-delay, 0s);\\n -webkit-animation-direction: var(--fa-animation-direction, normal);\\n animation-direction: var(--fa-animation-direction, normal);\\n -webkit-animation-duration: var(--fa-animation-duration, 2s);\\n animation-duration: var(--fa-animation-duration, 2s);\\n -webkit-animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n -webkit-animation-timing-function: var(--fa-animation-timing, linear);\\n animation-timing-function: var(--fa-animation-timing, linear);\\n}\\n\\n.fa-spin-reverse {\\n --fa-animation-direction: reverse;\\n}\\n\\n.fa-pulse,\\n.fa-spin-pulse {\\n -webkit-animation-name: fa-spin;\\n animation-name: fa-spin;\\n -webkit-animation-direction: var(--fa-animation-direction, normal);\\n animation-direction: var(--fa-animation-direction, normal);\\n -webkit-animation-duration: var(--fa-animation-duration, 1s);\\n animation-duration: var(--fa-animation-duration, 1s);\\n -webkit-animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n animation-iteration-count: var(--fa-animation-iteration-count, infinite);\\n -webkit-animation-timing-function: var(--fa-animation-timing, steps(8));\\n animation-timing-function: var(--fa-animation-timing, steps(8));\\n}\\n\\n@media (prefers-reduced-motion: reduce) {\\n .fa-beat,\\n.fa-bounce,\\n.fa-fade,\\n.fa-beat-fade,\\n.fa-flip,\\n.fa-pulse,\\n.fa-shake,\\n.fa-spin,\\n.fa-spin-pulse {\\n -webkit-animation-delay: -1ms;\\n animation-delay: -1ms;\\n -webkit-animation-duration: 1ms;\\n animation-duration: 1ms;\\n -webkit-animation-iteration-count: 1;\\n animation-iteration-count: 1;\\n -webkit-transition-delay: 0s;\\n transition-delay: 0s;\\n -webkit-transition-duration: 0s;\\n transition-duration: 0s;\\n }\\n}\\n@-webkit-keyframes fa-beat {\\n 0%, 90% {\\n -webkit-transform: scale(1);\\n transform: scale(1);\\n }\\n 45% {\\n -webkit-transform: scale(var(--fa-beat-scale, 1.25));\\n transform: scale(var(--fa-beat-scale, 1.25));\\n }\\n}\\n@keyframes fa-beat {\\n 0%, 90% {\\n -webkit-transform: scale(1);\\n transform: scale(1);\\n }\\n 45% {\\n -webkit-transform: scale(var(--fa-beat-scale, 1.25));\\n transform: scale(var(--fa-beat-scale, 1.25));\\n }\\n}\\n@-webkit-keyframes fa-bounce {\\n 0% {\\n -webkit-transform: scale(1, 1) translateY(0);\\n transform: scale(1, 1) translateY(0);\\n }\\n 10% {\\n -webkit-transform: scale(var(--fa-bounce-start-scale-x, 1.1), var(--fa-bounce-start-scale-y, 0.9)) translateY(0);\\n transform: scale(var(--fa-bounce-start-scale-x, 1.1), var(--fa-bounce-start-scale-y, 0.9)) translateY(0);\\n }\\n 30% {\\n -webkit-transform: scale(var(--fa-bounce-jump-scale-x, 0.9), var(--fa-bounce-jump-scale-y, 1.1)) translateY(var(--fa-bounce-height, -0.5em));\\n transform: scale(var(--fa-bounce-jump-scale-x, 0.9), var(--fa-bounce-jump-scale-y, 1.1)) translateY(var(--fa-bounce-height, -0.5em));\\n }\\n 50% {\\n -webkit-transform: scale(var(--fa-bounce-land-scale-x, 1.05), var(--fa-bounce-land-scale-y, 0.95)) translateY(0);\\n transform: scale(var(--fa-bounce-land-scale-x, 1.05), var(--fa-bounce-land-scale-y, 0.95)) translateY(0);\\n }\\n 57% {\\n -webkit-transform: scale(1, 1) translateY(var(--fa-bounce-rebound, -0.125em));\\n transform: scale(1, 1) translateY(var(--fa-bounce-rebound, -0.125em));\\n }\\n 64% {\\n -webkit-transform: scale(1, 1) translateY(0);\\n transform: scale(1, 1) translateY(0);\\n }\\n 100% {\\n -webkit-transform: scale(1, 1) translateY(0);\\n transform: scale(1, 1) translateY(0);\\n }\\n}\\n@keyframes fa-bounce {\\n 0% {\\n -webkit-transform: scale(1, 1) translateY(0);\\n transform: scale(1, 1) translateY(0);\\n }\\n 10% {\\n -webkit-transform: scale(var(--fa-bounce-start-scale-x, 1.1), var(--fa-bounce-start-scale-y, 0.9)) translateY(0);\\n transform: scale(var(--fa-bounce-start-scale-x, 1.1), var(--fa-bounce-start-scale-y, 0.9)) translateY(0);\\n }\\n 30% {\\n -webkit-transform: scale(var(--fa-bounce-jump-scale-x, 0.9), var(--fa-bounce-jump-scale-y, 1.1)) translateY(var(--fa-bounce-height, -0.5em));\\n transform: scale(var(--fa-bounce-jump-scale-x, 0.9), var(--fa-bounce-jump-scale-y, 1.1)) translateY(var(--fa-bounce-height, -0.5em));\\n }\\n 50% {\\n -webkit-transform: scale(var(--fa-bounce-land-scale-x, 1.05), var(--fa-bounce-land-scale-y, 0.95)) translateY(0);\\n transform: scale(var(--fa-bounce-land-scale-x, 1.05), var(--fa-bounce-land-scale-y, 0.95)) translateY(0);\\n }\\n 57% {\\n -webkit-transform: scale(1, 1) translateY(var(--fa-bounce-rebound, -0.125em));\\n transform: scale(1, 1) translateY(var(--fa-bounce-rebound, -0.125em));\\n }\\n 64% {\\n -webkit-transform: scale(1, 1) translateY(0);\\n transform: scale(1, 1) translateY(0);\\n }\\n 100% {\\n -webkit-transform: scale(1, 1) translateY(0);\\n transform: scale(1, 1) translateY(0);\\n }\\n}\\n@-webkit-keyframes fa-fade {\\n 50% {\\n opacity: var(--fa-fade-opacity, 0.4);\\n }\\n}\\n@keyframes fa-fade {\\n 50% {\\n opacity: var(--fa-fade-opacity, 0.4);\\n }\\n}\\n@-webkit-keyframes fa-beat-fade {\\n 0%, 100% {\\n opacity: var(--fa-beat-fade-opacity, 0.4);\\n -webkit-transform: scale(1);\\n transform: scale(1);\\n }\\n 50% {\\n opacity: 1;\\n -webkit-transform: scale(var(--fa-beat-fade-scale, 1.125));\\n transform: scale(var(--fa-beat-fade-scale, 1.125));\\n }\\n}\\n@keyframes fa-beat-fade {\\n 0%, 100% {\\n opacity: var(--fa-beat-fade-opacity, 0.4);\\n -webkit-transform: scale(1);\\n transform: scale(1);\\n }\\n 50% {\\n opacity: 1;\\n -webkit-transform: scale(var(--fa-beat-fade-scale, 1.125));\\n transform: scale(var(--fa-beat-fade-scale, 1.125));\\n }\\n}\\n@-webkit-keyframes fa-flip {\\n 50% {\\n -webkit-transform: rotate3d(var(--fa-flip-x, 0), var(--fa-flip-y, 1), var(--fa-flip-z, 0), var(--fa-flip-angle, -180deg));\\n transform: rotate3d(var(--fa-flip-x, 0), var(--fa-flip-y, 1), var(--fa-flip-z, 0), var(--fa-flip-angle, -180deg));\\n }\\n}\\n@keyframes fa-flip {\\n 50% {\\n -webkit-transform: rotate3d(var(--fa-flip-x, 0), var(--fa-flip-y, 1), var(--fa-flip-z, 0), var(--fa-flip-angle, -180deg));\\n transform: rotate3d(var(--fa-flip-x, 0), var(--fa-flip-y, 1), var(--fa-flip-z, 0), var(--fa-flip-angle, -180deg));\\n }\\n}\\n@-webkit-keyframes fa-shake {\\n 0% {\\n -webkit-transform: rotate(-15deg);\\n transform: rotate(-15deg);\\n }\\n 4% {\\n -webkit-transform: rotate(15deg);\\n transform: rotate(15deg);\\n }\\n 8%, 24% {\\n -webkit-transform: rotate(-18deg);\\n transform: rotate(-18deg);\\n }\\n 12%, 28% {\\n -webkit-transform: rotate(18deg);\\n transform: rotate(18deg);\\n }\\n 16% {\\n -webkit-transform: rotate(-22deg);\\n transform: rotate(-22deg);\\n }\\n 20% {\\n -webkit-transform: rotate(22deg);\\n transform: rotate(22deg);\\n }\\n 32% {\\n -webkit-transform: rotate(-12deg);\\n transform: rotate(-12deg);\\n }\\n 36% {\\n -webkit-transform: rotate(12deg);\\n transform: rotate(12deg);\\n }\\n 40%, 100% {\\n -webkit-transform: rotate(0deg);\\n transform: rotate(0deg);\\n }\\n}\\n@keyframes fa-shake {\\n 0% {\\n -webkit-transform: rotate(-15deg);\\n transform: rotate(-15deg);\\n }\\n 4% {\\n -webkit-transform: rotate(15deg);\\n transform: rotate(15deg);\\n }\\n 8%, 24% {\\n -webkit-transform: rotate(-18deg);\\n transform: rotate(-18deg);\\n }\\n 12%, 28% {\\n -webkit-transform: rotate(18deg);\\n transform: rotate(18deg);\\n }\\n 16% {\\n -webkit-transform: rotate(-22deg);\\n transform: rotate(-22deg);\\n }\\n 20% {\\n -webkit-transform: rotate(22deg);\\n transform: rotate(22deg);\\n }\\n 32% {\\n -webkit-transform: rotate(-12deg);\\n transform: rotate(-12deg);\\n }\\n 36% {\\n -webkit-transform: rotate(12deg);\\n transform: rotate(12deg);\\n }\\n 40%, 100% {\\n -webkit-transform: rotate(0deg);\\n transform: rotate(0deg);\\n }\\n}\\n@-webkit-keyframes fa-spin {\\n 0% {\\n -webkit-transform: rotate(0deg);\\n transform: rotate(0deg);\\n }\\n 100% {\\n -webkit-transform: rotate(360deg);\\n transform: rotate(360deg);\\n }\\n}\\n@keyframes fa-spin {\\n 0% {\\n -webkit-transform: rotate(0deg);\\n transform: rotate(0deg);\\n }\\n 100% {\\n -webkit-transform: rotate(360deg);\\n transform: rotate(360deg);\\n }\\n}\\n.fa-rotate-90 {\\n -webkit-transform: rotate(90deg);\\n transform: rotate(90deg);\\n}\\n\\n.fa-rotate-180 {\\n -webkit-transform: rotate(180deg);\\n transform: rotate(180deg);\\n}\\n\\n.fa-rotate-270 {\\n -webkit-transform: rotate(270deg);\\n transform: rotate(270deg);\\n}\\n\\n.fa-flip-horizontal {\\n -webkit-transform: scale(-1, 1);\\n transform: scale(-1, 1);\\n}\\n\\n.fa-flip-vertical {\\n -webkit-transform: scale(1, -1);\\n transform: scale(1, -1);\\n}\\n\\n.fa-flip-both,\\n.fa-flip-horizontal.fa-flip-vertical {\\n -webkit-transform: scale(-1, -1);\\n transform: scale(-1, -1);\\n}\\n\\n.fa-rotate-by {\\n -webkit-transform: rotate(var(--fa-rotate-angle, none));\\n transform: rotate(var(--fa-rotate-angle, none));\\n}\\n\\n.fa-stack {\\n display: inline-block;\\n vertical-align: middle;\\n height: 2em;\\n position: relative;\\n width: 2.5em;\\n}\\n\\n.fa-stack-1x,\\n.fa-stack-2x {\\n bottom: 0;\\n left: 0;\\n margin: auto;\\n position: absolute;\\n right: 0;\\n top: 0;\\n z-index: var(--fa-stack-z-index, auto);\\n}\\n\\n.svg-inline--fa.fa-stack-1x {\\n height: 1em;\\n width: 1.25em;\\n}\\n.svg-inline--fa.fa-stack-2x {\\n height: 2em;\\n width: 2.5em;\\n}\\n\\n.fa-inverse {\\n color: var(--fa-inverse, #fff);\\n}\\n\\n.sr-only,\\n.fa-sr-only {\\n position: absolute;\\n width: 1px;\\n height: 1px;\\n padding: 0;\\n margin: -1px;\\n overflow: hidden;\\n clip: rect(0, 0, 0, 0);\\n white-space: nowrap;\\n border-width: 0;\\n}\\n\\n.sr-only-focusable:not(:focus),\\n.fa-sr-only-focusable:not(:focus) {\\n position: absolute;\\n width: 1px;\\n height: 1px;\\n padding: 0;\\n margin: -1px;\\n overflow: hidden;\\n clip: rect(0, 0, 0, 0);\\n white-space: nowrap;\\n border-width: 0;\\n}\\n\\n.svg-inline--fa .fa-primary {\\n fill: var(--fa-primary-color, currentColor);\\n opacity: var(--fa-primary-opacity, 1);\\n}\\n\\n.svg-inline--fa .fa-secondary {\\n fill: var(--fa-secondary-color, currentColor);\\n opacity: var(--fa-secondary-opacity, 0.4);\\n}\\n\\n.svg-inline--fa.fa-swap-opacity .fa-primary {\\n opacity: var(--fa-secondary-opacity, 0.4);\\n}\\n\\n.svg-inline--fa.fa-swap-opacity .fa-secondary {\\n opacity: var(--fa-primary-opacity, 1);\\n}\\n\\n.svg-inline--fa mask .fa-primary,\\n.svg-inline--fa mask .fa-secondary {\\n fill: black;\\n}\\n\\n.fad.fa-inverse,\\n.fa-duotone.fa-inverse {\\n color: var(--fa-inverse, #fff);\\n}\";\n\nfunction css() {\n var dcp = DEFAULT_CSS_PREFIX;\n var drc = DEFAULT_REPLACEMENT_CLASS;\n var fp = config.cssPrefix;\n var rc = config.replacementClass;\n var s = baseStyles;\n\n if (fp !== dcp || rc !== drc) {\n var dPatt = new RegExp(\"\\\\.\".concat(dcp, \"\\\\-\"), 'g');\n var customPropPatt = new RegExp(\"\\\\--\".concat(dcp, \"\\\\-\"), 'g');\n var rPatt = new RegExp(\"\\\\.\".concat(drc), 'g');\n s = s.replace(dPatt, \".\".concat(fp, \"-\")).replace(customPropPatt, \"--\".concat(fp, \"-\")).replace(rPatt, \".\".concat(rc));\n }\n\n return s;\n}\n\nvar _cssInserted = false;\n\nfunction ensureCss() {\n if (config.autoAddCss && !_cssInserted) {\n insertCss(css());\n _cssInserted = true;\n }\n}\n\nvar InjectCSS = {\n mixout: function mixout() {\n return {\n dom: {\n css: css,\n insertCss: ensureCss\n }\n };\n },\n hooks: function hooks() {\n return {\n beforeDOMElementCreation: function beforeDOMElementCreation() {\n ensureCss();\n },\n beforeI2svg: function beforeI2svg() {\n ensureCss();\n }\n };\n }\n};\n\nvar w = WINDOW || {};\nif (!w[NAMESPACE_IDENTIFIER]) w[NAMESPACE_IDENTIFIER] = {};\nif (!w[NAMESPACE_IDENTIFIER].styles) w[NAMESPACE_IDENTIFIER].styles = {};\nif (!w[NAMESPACE_IDENTIFIER].hooks) w[NAMESPACE_IDENTIFIER].hooks = {};\nif (!w[NAMESPACE_IDENTIFIER].shims) w[NAMESPACE_IDENTIFIER].shims = [];\nvar namespace = w[NAMESPACE_IDENTIFIER];\n\nvar functions = [];\n\nvar listener = function listener() {\n DOCUMENT.removeEventListener('DOMContentLoaded', listener);\n loaded = 1;\n functions.map(function (fn) {\n return fn();\n });\n};\n\nvar loaded = false;\n\nif (IS_DOM) {\n loaded = (DOCUMENT.documentElement.doScroll ? /^loaded|^c/ : /^loaded|^i|^c/).test(DOCUMENT.readyState);\n if (!loaded) DOCUMENT.addEventListener('DOMContentLoaded', listener);\n}\n\nfunction domready (fn) {\n if (!IS_DOM) return;\n loaded ? setTimeout(fn, 0) : functions.push(fn);\n}\n\nfunction toHtml(abstractNodes) {\n var tag = abstractNodes.tag,\n _abstractNodes$attrib = abstractNodes.attributes,\n attributes = _abstractNodes$attrib === void 0 ? {} : _abstractNodes$attrib,\n _abstractNodes$childr = abstractNodes.children,\n children = _abstractNodes$childr === void 0 ? [] : _abstractNodes$childr;\n\n if (typeof abstractNodes === 'string') {\n return htmlEscape(abstractNodes);\n } else {\n return \"<\".concat(tag, \" \").concat(joinAttributes(attributes), \">\").concat(children.map(toHtml).join(''), \"\");\n }\n}\n\nfunction iconFromMapping(mapping, prefix, iconName) {\n if (mapping && mapping[prefix] && mapping[prefix][iconName]) {\n return {\n prefix: prefix,\n iconName: iconName,\n icon: mapping[prefix][iconName]\n };\n }\n}\n\n/**\n * Internal helper to bind a function known to have 4 arguments\n * to a given context.\n */\n\nvar bindInternal4 = function bindInternal4(func, thisContext) {\n return function (a, b, c, d) {\n return func.call(thisContext, a, b, c, d);\n };\n};\n\n/**\n * # Reduce\n *\n * A fast object `.reduce()` implementation.\n *\n * @param {Object} subject The object to reduce over.\n * @param {Function} fn The reducer function.\n * @param {mixed} initialValue The initial value for the reducer, defaults to subject[0].\n * @param {Object} thisContext The context for the reducer.\n * @return {mixed} The final result.\n */\n\n\nvar reduce = function fastReduceObject(subject, fn, initialValue, thisContext) {\n var keys = Object.keys(subject),\n length = keys.length,\n iterator = thisContext !== undefined ? bindInternal4(fn, thisContext) : fn,\n i,\n key,\n result;\n\n if (initialValue === undefined) {\n i = 1;\n result = subject[keys[0]];\n } else {\n i = 0;\n result = initialValue;\n }\n\n for (; i < length; i++) {\n key = keys[i];\n result = iterator(result, subject[key], key, subject);\n }\n\n return result;\n};\n\n/**\n * ucs2decode() and codePointAt() are both works of Mathias Bynens and licensed under MIT\n *\n * Copyright Mathias Bynens \n\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nfunction ucs2decode(string) {\n var output = [];\n var counter = 0;\n var length = string.length;\n\n while (counter < length) {\n var value = string.charCodeAt(counter++);\n\n if (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n var extra = string.charCodeAt(counter++);\n\n if ((extra & 0xFC00) == 0xDC00) {\n // eslint-disable-line eqeqeq\n output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n } else {\n output.push(value);\n counter--;\n }\n } else {\n output.push(value);\n }\n }\n\n return output;\n}\n\nfunction toHex(unicode) {\n var decoded = ucs2decode(unicode);\n return decoded.length === 1 ? decoded[0].toString(16) : null;\n}\nfunction codePointAt(string, index) {\n var size = string.length;\n var first = string.charCodeAt(index);\n var second;\n\n if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {\n second = string.charCodeAt(index + 1);\n\n if (second >= 0xDC00 && second <= 0xDFFF) {\n return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;\n }\n }\n\n return first;\n}\n\nfunction normalizeIcons(icons) {\n return Object.keys(icons).reduce(function (acc, iconName) {\n var icon = icons[iconName];\n var expanded = !!icon.icon;\n\n if (expanded) {\n acc[icon.iconName] = icon.icon;\n } else {\n acc[iconName] = icon;\n }\n\n return acc;\n }, {});\n}\n\nfunction defineIcons(prefix, icons) {\n var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var _params$skipHooks = params.skipHooks,\n skipHooks = _params$skipHooks === void 0 ? false : _params$skipHooks;\n var normalized = normalizeIcons(icons);\n\n if (typeof namespace.hooks.addPack === 'function' && !skipHooks) {\n namespace.hooks.addPack(prefix, normalizeIcons(icons));\n } else {\n namespace.styles[prefix] = _objectSpread2(_objectSpread2({}, namespace.styles[prefix] || {}), normalized);\n }\n /**\n * Font Awesome 4 used the prefix of `fa` for all icons. With the introduction\n * of new styles we needed to differentiate between them. Prefix `fa` is now an alias\n * for `fas` so we'll ease the upgrade process for our users by automatically defining\n * this as well.\n */\n\n\n if (prefix === 'fas') {\n defineIcons('fa', icons);\n }\n}\n\nvar duotonePathRe = [/*#__PURE__*/_wrapRegExp(/path d=\"((?:(?!\")[\\s\\S])+)\".*path d=\"((?:(?!\")[\\s\\S])+)\"/, {\n d1: 1,\n d2: 2\n}), /*#__PURE__*/_wrapRegExp(/path class=\"((?:(?!\")[\\s\\S])+)\".*d=\"((?:(?!\")[\\s\\S])+)\".*path class=\"((?:(?!\")[\\s\\S])+)\".*d=\"((?:(?!\")[\\s\\S])+)\"/, {\n cls1: 1,\n d1: 2,\n cls2: 3,\n d2: 4\n}), /*#__PURE__*/_wrapRegExp(/path class=\"((?:(?!\")[\\s\\S])+)\".*d=\"((?:(?!\")[\\s\\S])+)\"/, {\n cls1: 1,\n d1: 2\n})];\n\nvar _LONG_STYLE, _PREFIXES, _PREFIXES_FOR_FAMILY;\nvar styles = namespace.styles,\n shims = namespace.shims;\nvar LONG_STYLE = (_LONG_STYLE = {}, _defineProperty(_LONG_STYLE, FAMILY_CLASSIC, Object.values(PREFIX_TO_LONG_STYLE[FAMILY_CLASSIC])), _defineProperty(_LONG_STYLE, FAMILY_SHARP, Object.values(PREFIX_TO_LONG_STYLE[FAMILY_SHARP])), _LONG_STYLE);\nvar _defaultUsablePrefix = null;\nvar _byUnicode = {};\nvar _byLigature = {};\nvar _byOldName = {};\nvar _byOldUnicode = {};\nvar _byAlias = {};\nvar PREFIXES = (_PREFIXES = {}, _defineProperty(_PREFIXES, FAMILY_CLASSIC, Object.keys(PREFIX_TO_STYLE[FAMILY_CLASSIC])), _defineProperty(_PREFIXES, FAMILY_SHARP, Object.keys(PREFIX_TO_STYLE[FAMILY_SHARP])), _PREFIXES);\n\nfunction isReserved(name) {\n return ~RESERVED_CLASSES.indexOf(name);\n}\n\nfunction getIconName(cssPrefix, cls) {\n var parts = cls.split('-');\n var prefix = parts[0];\n var iconName = parts.slice(1).join('-');\n\n if (prefix === cssPrefix && iconName !== '' && !isReserved(iconName)) {\n return iconName;\n } else {\n return null;\n }\n}\nvar build = function build() {\n var lookup = function lookup(reducer) {\n return reduce(styles, function (o, style, prefix) {\n o[prefix] = reduce(style, reducer, {});\n return o;\n }, {});\n };\n\n _byUnicode = lookup(function (acc, icon, iconName) {\n if (icon[3]) {\n acc[icon[3]] = iconName;\n }\n\n if (icon[2]) {\n var aliases = icon[2].filter(function (a) {\n return typeof a === 'number';\n });\n aliases.forEach(function (alias) {\n acc[alias.toString(16)] = iconName;\n });\n }\n\n return acc;\n });\n _byLigature = lookup(function (acc, icon, iconName) {\n acc[iconName] = iconName;\n\n if (icon[2]) {\n var aliases = icon[2].filter(function (a) {\n return typeof a === 'string';\n });\n aliases.forEach(function (alias) {\n acc[alias] = iconName;\n });\n }\n\n return acc;\n });\n _byAlias = lookup(function (acc, icon, iconName) {\n var aliases = icon[2];\n acc[iconName] = iconName;\n aliases.forEach(function (alias) {\n acc[alias] = iconName;\n });\n return acc;\n }); // If we have a Kit, we can't determine if regular is available since we\n // could be auto-fetching it. We'll have to assume that it is available.\n\n var hasRegular = 'far' in styles || config.autoFetchSvg;\n var shimLookups = reduce(shims, function (acc, shim) {\n var maybeNameMaybeUnicode = shim[0];\n var prefix = shim[1];\n var iconName = shim[2];\n\n if (prefix === 'far' && !hasRegular) {\n prefix = 'fas';\n }\n\n if (typeof maybeNameMaybeUnicode === 'string') {\n acc.names[maybeNameMaybeUnicode] = {\n prefix: prefix,\n iconName: iconName\n };\n }\n\n if (typeof maybeNameMaybeUnicode === 'number') {\n acc.unicodes[maybeNameMaybeUnicode.toString(16)] = {\n prefix: prefix,\n iconName: iconName\n };\n }\n\n return acc;\n }, {\n names: {},\n unicodes: {}\n });\n _byOldName = shimLookups.names;\n _byOldUnicode = shimLookups.unicodes;\n _defaultUsablePrefix = getCanonicalPrefix(config.styleDefault, {\n family: config.familyDefault\n });\n};\nonChange(function (c) {\n _defaultUsablePrefix = getCanonicalPrefix(c.styleDefault, {\n family: config.familyDefault\n });\n});\nbuild();\nfunction byUnicode(prefix, unicode) {\n return (_byUnicode[prefix] || {})[unicode];\n}\nfunction byLigature(prefix, ligature) {\n return (_byLigature[prefix] || {})[ligature];\n}\nfunction byAlias(prefix, alias) {\n return (_byAlias[prefix] || {})[alias];\n}\nfunction byOldName(name) {\n return _byOldName[name] || {\n prefix: null,\n iconName: null\n };\n}\nfunction byOldUnicode(unicode) {\n var oldUnicode = _byOldUnicode[unicode];\n var newUnicode = byUnicode('fas', unicode);\n return oldUnicode || (newUnicode ? {\n prefix: 'fas',\n iconName: newUnicode\n } : null) || {\n prefix: null,\n iconName: null\n };\n}\nfunction getDefaultUsablePrefix() {\n return _defaultUsablePrefix;\n}\nvar emptyCanonicalIcon = function emptyCanonicalIcon() {\n return {\n prefix: null,\n iconName: null,\n rest: []\n };\n};\nfunction getCanonicalPrefix(styleOrPrefix) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _params$family = params.family,\n family = _params$family === void 0 ? FAMILY_CLASSIC : _params$family;\n var style = PREFIX_TO_STYLE[family][styleOrPrefix];\n var prefix = STYLE_TO_PREFIX[family][styleOrPrefix] || STYLE_TO_PREFIX[family][style];\n var defined = styleOrPrefix in namespace.styles ? styleOrPrefix : null;\n return prefix || defined || null;\n}\nvar PREFIXES_FOR_FAMILY = (_PREFIXES_FOR_FAMILY = {}, _defineProperty(_PREFIXES_FOR_FAMILY, FAMILY_CLASSIC, Object.keys(PREFIX_TO_LONG_STYLE[FAMILY_CLASSIC])), _defineProperty(_PREFIXES_FOR_FAMILY, FAMILY_SHARP, Object.keys(PREFIX_TO_LONG_STYLE[FAMILY_SHARP])), _PREFIXES_FOR_FAMILY);\nfunction getCanonicalIcon(values) {\n var _famProps;\n\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _params$skipLookups = params.skipLookups,\n skipLookups = _params$skipLookups === void 0 ? false : _params$skipLookups;\n var famProps = (_famProps = {}, _defineProperty(_famProps, FAMILY_CLASSIC, \"\".concat(config.cssPrefix, \"-\").concat(FAMILY_CLASSIC)), _defineProperty(_famProps, FAMILY_SHARP, \"\".concat(config.cssPrefix, \"-\").concat(FAMILY_SHARP)), _famProps);\n var givenPrefix = null;\n var family = FAMILY_CLASSIC;\n\n if (values.includes(famProps[FAMILY_CLASSIC]) || values.some(function (v) {\n return PREFIXES_FOR_FAMILY[FAMILY_CLASSIC].includes(v);\n })) {\n family = FAMILY_CLASSIC;\n }\n\n if (values.includes(famProps[FAMILY_SHARP]) || values.some(function (v) {\n return PREFIXES_FOR_FAMILY[FAMILY_SHARP].includes(v);\n })) {\n family = FAMILY_SHARP;\n }\n\n var canonical = values.reduce(function (acc, cls) {\n var iconName = getIconName(config.cssPrefix, cls);\n\n if (styles[cls]) {\n cls = LONG_STYLE[family].includes(cls) ? LONG_STYLE_TO_PREFIX[family][cls] : cls;\n givenPrefix = cls;\n acc.prefix = cls;\n } else if (PREFIXES[family].indexOf(cls) > -1) {\n givenPrefix = cls;\n acc.prefix = getCanonicalPrefix(cls, {\n family: family\n });\n } else if (iconName) {\n acc.iconName = iconName;\n } else if (cls !== config.replacementClass && cls !== famProps[FAMILY_CLASSIC] && cls !== famProps[FAMILY_SHARP]) {\n acc.rest.push(cls);\n }\n\n if (!skipLookups && acc.prefix && acc.iconName) {\n var shim = givenPrefix === 'fa' ? byOldName(acc.iconName) : {};\n var aliasIconName = byAlias(acc.prefix, acc.iconName);\n\n if (shim.prefix) {\n givenPrefix = null;\n }\n\n acc.iconName = shim.iconName || aliasIconName || acc.iconName;\n acc.prefix = shim.prefix || acc.prefix;\n\n if (acc.prefix === 'far' && !styles['far'] && styles['fas'] && !config.autoFetchSvg) {\n // Allow a fallback from the regular style to solid if regular is not available\n // but only if we aren't auto-fetching SVGs\n acc.prefix = 'fas';\n }\n }\n\n return acc;\n }, emptyCanonicalIcon());\n\n if (values.includes('fa-brands') || values.includes('fab')) {\n canonical.prefix = 'fab';\n }\n\n if (values.includes('fa-duotone') || values.includes('fad')) {\n canonical.prefix = 'fad';\n }\n\n if (!canonical.prefix && family === FAMILY_SHARP && (styles['fass'] || config.autoFetchSvg)) {\n canonical.prefix = 'fass';\n canonical.iconName = byAlias(canonical.prefix, canonical.iconName) || canonical.iconName;\n }\n\n if (canonical.prefix === 'fa' || givenPrefix === 'fa') {\n // The fa prefix is not canonical. So if it has made it through until this point\n // we will shift it to the correct prefix.\n canonical.prefix = getDefaultUsablePrefix() || 'fas';\n }\n\n return canonical;\n}\n\nvar Library = /*#__PURE__*/function () {\n function Library() {\n _classCallCheck(this, Library);\n\n this.definitions = {};\n }\n\n _createClass(Library, [{\n key: \"add\",\n value: function add() {\n var _this = this;\n\n for (var _len = arguments.length, definitions = new Array(_len), _key = 0; _key < _len; _key++) {\n definitions[_key] = arguments[_key];\n }\n\n var additions = definitions.reduce(this._pullDefinitions, {});\n Object.keys(additions).forEach(function (key) {\n _this.definitions[key] = _objectSpread2(_objectSpread2({}, _this.definitions[key] || {}), additions[key]);\n defineIcons(key, additions[key]); // TODO can we stop doing this? We can't get the icons by 'fa-solid' any longer so this probably needs to change\n\n var longPrefix = PREFIX_TO_LONG_STYLE[FAMILY_CLASSIC][key];\n if (longPrefix) defineIcons(longPrefix, additions[key]);\n build();\n });\n }\n }, {\n key: \"reset\",\n value: function reset() {\n this.definitions = {};\n }\n }, {\n key: \"_pullDefinitions\",\n value: function _pullDefinitions(additions, definition) {\n var normalized = definition.prefix && definition.iconName && definition.icon ? {\n 0: definition\n } : definition;\n Object.keys(normalized).map(function (key) {\n var _normalized$key = normalized[key],\n prefix = _normalized$key.prefix,\n iconName = _normalized$key.iconName,\n icon = _normalized$key.icon;\n var aliases = icon[2];\n if (!additions[prefix]) additions[prefix] = {};\n\n if (aliases.length > 0) {\n aliases.forEach(function (alias) {\n if (typeof alias === 'string') {\n additions[prefix][alias] = icon;\n }\n });\n }\n\n additions[prefix][iconName] = icon;\n });\n return additions;\n }\n }]);\n\n return Library;\n}();\n\nvar _plugins = [];\nvar _hooks = {};\nvar providers = {};\nvar defaultProviderKeys = Object.keys(providers);\nfunction registerPlugins(nextPlugins, _ref) {\n var obj = _ref.mixoutsTo;\n _plugins = nextPlugins;\n _hooks = {};\n Object.keys(providers).forEach(function (k) {\n if (defaultProviderKeys.indexOf(k) === -1) {\n delete providers[k];\n }\n });\n\n _plugins.forEach(function (plugin) {\n var mixout = plugin.mixout ? plugin.mixout() : {};\n Object.keys(mixout).forEach(function (tk) {\n if (typeof mixout[tk] === 'function') {\n obj[tk] = mixout[tk];\n }\n\n if (_typeof(mixout[tk]) === 'object') {\n Object.keys(mixout[tk]).forEach(function (sk) {\n if (!obj[tk]) {\n obj[tk] = {};\n }\n\n obj[tk][sk] = mixout[tk][sk];\n });\n }\n });\n\n if (plugin.hooks) {\n var hooks = plugin.hooks();\n Object.keys(hooks).forEach(function (hook) {\n if (!_hooks[hook]) {\n _hooks[hook] = [];\n }\n\n _hooks[hook].push(hooks[hook]);\n });\n }\n\n if (plugin.provides) {\n plugin.provides(providers);\n }\n });\n\n return obj;\n}\nfunction chainHooks(hook, accumulator) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n\n var hookFns = _hooks[hook] || [];\n hookFns.forEach(function (hookFn) {\n accumulator = hookFn.apply(null, [accumulator].concat(args)); // eslint-disable-line no-useless-call\n });\n return accumulator;\n}\nfunction callHooks(hook) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n var hookFns = _hooks[hook] || [];\n hookFns.forEach(function (hookFn) {\n hookFn.apply(null, args);\n });\n return undefined;\n}\nfunction callProvided() {\n var hook = arguments[0];\n var args = Array.prototype.slice.call(arguments, 1);\n return providers[hook] ? providers[hook].apply(null, args) : undefined;\n}\n\nfunction findIconDefinition(iconLookup) {\n if (iconLookup.prefix === 'fa') {\n iconLookup.prefix = 'fas';\n }\n\n var iconName = iconLookup.iconName;\n var prefix = iconLookup.prefix || getDefaultUsablePrefix();\n if (!iconName) return;\n iconName = byAlias(prefix, iconName) || iconName;\n return iconFromMapping(library.definitions, prefix, iconName) || iconFromMapping(namespace.styles, prefix, iconName);\n}\nvar library = new Library();\nvar noAuto = function noAuto() {\n config.autoReplaceSvg = false;\n config.observeMutations = false;\n callHooks('noAuto');\n};\nvar dom = {\n i2svg: function i2svg() {\n var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n if (IS_DOM) {\n callHooks('beforeI2svg', params);\n callProvided('pseudoElements2svg', params);\n return callProvided('i2svg', params);\n } else {\n return Promise.reject('Operation requires a DOM of some kind.');\n }\n },\n watch: function watch() {\n var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var autoReplaceSvgRoot = params.autoReplaceSvgRoot;\n\n if (config.autoReplaceSvg === false) {\n config.autoReplaceSvg = true;\n }\n\n config.observeMutations = true;\n domready(function () {\n autoReplace({\n autoReplaceSvgRoot: autoReplaceSvgRoot\n });\n callHooks('watch', params);\n });\n }\n};\nvar parse = {\n icon: function icon(_icon) {\n if (_icon === null) {\n return null;\n }\n\n if (_typeof(_icon) === 'object' && _icon.prefix && _icon.iconName) {\n return {\n prefix: _icon.prefix,\n iconName: byAlias(_icon.prefix, _icon.iconName) || _icon.iconName\n };\n }\n\n if (Array.isArray(_icon) && _icon.length === 2) {\n var iconName = _icon[1].indexOf('fa-') === 0 ? _icon[1].slice(3) : _icon[1];\n var prefix = getCanonicalPrefix(_icon[0]);\n return {\n prefix: prefix,\n iconName: byAlias(prefix, iconName) || iconName\n };\n }\n\n if (typeof _icon === 'string' && (_icon.indexOf(\"\".concat(config.cssPrefix, \"-\")) > -1 || _icon.match(ICON_SELECTION_SYNTAX_PATTERN))) {\n var canonicalIcon = getCanonicalIcon(_icon.split(' '), {\n skipLookups: true\n });\n return {\n prefix: canonicalIcon.prefix || getDefaultUsablePrefix(),\n iconName: byAlias(canonicalIcon.prefix, canonicalIcon.iconName) || canonicalIcon.iconName\n };\n }\n\n if (typeof _icon === 'string') {\n var _prefix = getDefaultUsablePrefix();\n\n return {\n prefix: _prefix,\n iconName: byAlias(_prefix, _icon) || _icon\n };\n }\n }\n};\nvar api = {\n noAuto: noAuto,\n config: config,\n dom: dom,\n parse: parse,\n library: library,\n findIconDefinition: findIconDefinition,\n toHtml: toHtml\n};\n\nvar autoReplace = function autoReplace() {\n var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var _params$autoReplaceSv = params.autoReplaceSvgRoot,\n autoReplaceSvgRoot = _params$autoReplaceSv === void 0 ? DOCUMENT : _params$autoReplaceSv;\n if ((Object.keys(namespace.styles).length > 0 || config.autoFetchSvg) && IS_DOM && config.autoReplaceSvg) api.dom.i2svg({\n node: autoReplaceSvgRoot\n });\n};\n\nfunction domVariants(val, abstractCreator) {\n Object.defineProperty(val, 'abstract', {\n get: abstractCreator\n });\n Object.defineProperty(val, 'html', {\n get: function get() {\n return val.abstract.map(function (a) {\n return toHtml(a);\n });\n }\n });\n Object.defineProperty(val, 'node', {\n get: function get() {\n if (!IS_DOM) return;\n var container = DOCUMENT.createElement('div');\n container.innerHTML = val.html;\n return container.children;\n }\n });\n return val;\n}\n\nfunction asIcon (_ref) {\n var children = _ref.children,\n main = _ref.main,\n mask = _ref.mask,\n attributes = _ref.attributes,\n styles = _ref.styles,\n transform = _ref.transform;\n\n if (transformIsMeaningful(transform) && main.found && !mask.found) {\n var width = main.width,\n height = main.height;\n var offset = {\n x: width / height / 2,\n y: 0.5\n };\n attributes['style'] = joinStyles(_objectSpread2(_objectSpread2({}, styles), {}, {\n 'transform-origin': \"\".concat(offset.x + transform.x / 16, \"em \").concat(offset.y + transform.y / 16, \"em\")\n }));\n }\n\n return [{\n tag: 'svg',\n attributes: attributes,\n children: children\n }];\n}\n\nfunction asSymbol (_ref) {\n var prefix = _ref.prefix,\n iconName = _ref.iconName,\n children = _ref.children,\n attributes = _ref.attributes,\n symbol = _ref.symbol;\n var id = symbol === true ? \"\".concat(prefix, \"-\").concat(config.cssPrefix, \"-\").concat(iconName) : symbol;\n return [{\n tag: 'svg',\n attributes: {\n style: 'display: none;'\n },\n children: [{\n tag: 'symbol',\n attributes: _objectSpread2(_objectSpread2({}, attributes), {}, {\n id: id\n }),\n children: children\n }]\n }];\n}\n\nfunction makeInlineSvgAbstract(params) {\n var _params$icons = params.icons,\n main = _params$icons.main,\n mask = _params$icons.mask,\n prefix = params.prefix,\n iconName = params.iconName,\n transform = params.transform,\n symbol = params.symbol,\n title = params.title,\n maskId = params.maskId,\n titleId = params.titleId,\n extra = params.extra,\n _params$watchable = params.watchable,\n watchable = _params$watchable === void 0 ? false : _params$watchable;\n\n var _ref = mask.found ? mask : main,\n width = _ref.width,\n height = _ref.height;\n\n var isUploadedIcon = prefix === 'fak';\n var attrClass = [config.replacementClass, iconName ? \"\".concat(config.cssPrefix, \"-\").concat(iconName) : ''].filter(function (c) {\n return extra.classes.indexOf(c) === -1;\n }).filter(function (c) {\n return c !== '' || !!c;\n }).concat(extra.classes).join(' ');\n var content = {\n children: [],\n attributes: _objectSpread2(_objectSpread2({}, extra.attributes), {}, {\n 'data-prefix': prefix,\n 'data-icon': iconName,\n 'class': attrClass,\n 'role': extra.attributes.role || 'img',\n 'xmlns': 'http://www.w3.org/2000/svg',\n 'viewBox': \"0 0 \".concat(width, \" \").concat(height)\n })\n };\n var uploadedIconWidthStyle = isUploadedIcon && !~extra.classes.indexOf('fa-fw') ? {\n width: \"\".concat(width / height * 16 * 0.0625, \"em\")\n } : {};\n\n if (watchable) {\n content.attributes[DATA_FA_I2SVG] = '';\n }\n\n if (title) {\n content.children.push({\n tag: 'title',\n attributes: {\n id: content.attributes['aria-labelledby'] || \"title-\".concat(titleId || nextUniqueId())\n },\n children: [title]\n });\n delete content.attributes.title;\n }\n\n var args = _objectSpread2(_objectSpread2({}, content), {}, {\n prefix: prefix,\n iconName: iconName,\n main: main,\n mask: mask,\n maskId: maskId,\n transform: transform,\n symbol: symbol,\n styles: _objectSpread2(_objectSpread2({}, uploadedIconWidthStyle), extra.styles)\n });\n\n var _ref2 = mask.found && main.found ? callProvided('generateAbstractMask', args) || {\n children: [],\n attributes: {}\n } : callProvided('generateAbstractIcon', args) || {\n children: [],\n attributes: {}\n },\n children = _ref2.children,\n attributes = _ref2.attributes;\n\n args.children = children;\n args.attributes = attributes;\n\n if (symbol) {\n return asSymbol(args);\n } else {\n return asIcon(args);\n }\n}\nfunction makeLayersTextAbstract(params) {\n var content = params.content,\n width = params.width,\n height = params.height,\n transform = params.transform,\n title = params.title,\n extra = params.extra,\n _params$watchable2 = params.watchable,\n watchable = _params$watchable2 === void 0 ? false : _params$watchable2;\n\n var attributes = _objectSpread2(_objectSpread2(_objectSpread2({}, extra.attributes), title ? {\n 'title': title\n } : {}), {}, {\n 'class': extra.classes.join(' ')\n });\n\n if (watchable) {\n attributes[DATA_FA_I2SVG] = '';\n }\n\n var styles = _objectSpread2({}, extra.styles);\n\n if (transformIsMeaningful(transform)) {\n styles['transform'] = transformForCss({\n transform: transform,\n startCentered: true,\n width: width,\n height: height\n });\n styles['-webkit-transform'] = styles['transform'];\n }\n\n var styleString = joinStyles(styles);\n\n if (styleString.length > 0) {\n attributes['style'] = styleString;\n }\n\n var val = [];\n val.push({\n tag: 'span',\n attributes: attributes,\n children: [content]\n });\n\n if (title) {\n val.push({\n tag: 'span',\n attributes: {\n class: 'sr-only'\n },\n children: [title]\n });\n }\n\n return val;\n}\nfunction makeLayersCounterAbstract(params) {\n var content = params.content,\n title = params.title,\n extra = params.extra;\n\n var attributes = _objectSpread2(_objectSpread2(_objectSpread2({}, extra.attributes), title ? {\n 'title': title\n } : {}), {}, {\n 'class': extra.classes.join(' ')\n });\n\n var styleString = joinStyles(extra.styles);\n\n if (styleString.length > 0) {\n attributes['style'] = styleString;\n }\n\n var val = [];\n val.push({\n tag: 'span',\n attributes: attributes,\n children: [content]\n });\n\n if (title) {\n val.push({\n tag: 'span',\n attributes: {\n class: 'sr-only'\n },\n children: [title]\n });\n }\n\n return val;\n}\n\nvar styles$1 = namespace.styles;\nfunction asFoundIcon(icon) {\n var width = icon[0];\n var height = icon[1];\n\n var _icon$slice = icon.slice(4),\n _icon$slice2 = _slicedToArray(_icon$slice, 1),\n vectorData = _icon$slice2[0];\n\n var element = null;\n\n if (Array.isArray(vectorData)) {\n element = {\n tag: 'g',\n attributes: {\n class: \"\".concat(config.cssPrefix, \"-\").concat(DUOTONE_CLASSES.GROUP)\n },\n children: [{\n tag: 'path',\n attributes: {\n class: \"\".concat(config.cssPrefix, \"-\").concat(DUOTONE_CLASSES.SECONDARY),\n fill: 'currentColor',\n d: vectorData[0]\n }\n }, {\n tag: 'path',\n attributes: {\n class: \"\".concat(config.cssPrefix, \"-\").concat(DUOTONE_CLASSES.PRIMARY),\n fill: 'currentColor',\n d: vectorData[1]\n }\n }]\n };\n } else {\n element = {\n tag: 'path',\n attributes: {\n fill: 'currentColor',\n d: vectorData\n }\n };\n }\n\n return {\n found: true,\n width: width,\n height: height,\n icon: element\n };\n}\nvar missingIconResolutionMixin = {\n found: false,\n width: 512,\n height: 512\n};\n\nfunction maybeNotifyMissing(iconName, prefix) {\n if (!PRODUCTION && !config.showMissingIcons && iconName) {\n console.error(\"Icon with name \\\"\".concat(iconName, \"\\\" and prefix \\\"\").concat(prefix, \"\\\" is missing.\"));\n }\n}\n\nfunction findIcon(iconName, prefix) {\n var givenPrefix = prefix;\n\n if (prefix === 'fa' && config.styleDefault !== null) {\n prefix = getDefaultUsablePrefix();\n }\n\n return new Promise(function (resolve, reject) {\n var val = {\n found: false,\n width: 512,\n height: 512,\n icon: callProvided('missingIconAbstract') || {}\n };\n\n if (givenPrefix === 'fa') {\n var shim = byOldName(iconName) || {};\n iconName = shim.iconName || iconName;\n prefix = shim.prefix || prefix;\n }\n\n if (iconName && prefix && styles$1[prefix] && styles$1[prefix][iconName]) {\n var icon = styles$1[prefix][iconName];\n return resolve(asFoundIcon(icon));\n }\n\n maybeNotifyMissing(iconName, prefix);\n resolve(_objectSpread2(_objectSpread2({}, missingIconResolutionMixin), {}, {\n icon: config.showMissingIcons && iconName ? callProvided('missingIconAbstract') || {} : {}\n }));\n });\n}\n\nvar noop$1 = function noop() {};\n\nvar p = config.measurePerformance && PERFORMANCE && PERFORMANCE.mark && PERFORMANCE.measure ? PERFORMANCE : {\n mark: noop$1,\n measure: noop$1\n};\nvar preamble = \"FA \\\"6.5.1\\\"\";\n\nvar begin = function begin(name) {\n p.mark(\"\".concat(preamble, \" \").concat(name, \" begins\"));\n return function () {\n return end(name);\n };\n};\n\nvar end = function end(name) {\n p.mark(\"\".concat(preamble, \" \").concat(name, \" ends\"));\n p.measure(\"\".concat(preamble, \" \").concat(name), \"\".concat(preamble, \" \").concat(name, \" begins\"), \"\".concat(preamble, \" \").concat(name, \" ends\"));\n};\n\nvar perf = {\n begin: begin,\n end: end\n};\n\nvar noop$2 = function noop() {};\n\nfunction isWatched(node) {\n var i2svg = node.getAttribute ? node.getAttribute(DATA_FA_I2SVG) : null;\n return typeof i2svg === 'string';\n}\n\nfunction hasPrefixAndIcon(node) {\n var prefix = node.getAttribute ? node.getAttribute(DATA_PREFIX) : null;\n var icon = node.getAttribute ? node.getAttribute(DATA_ICON) : null;\n return prefix && icon;\n}\n\nfunction hasBeenReplaced(node) {\n return node && node.classList && node.classList.contains && node.classList.contains(config.replacementClass);\n}\n\nfunction getMutator() {\n if (config.autoReplaceSvg === true) {\n return mutators.replace;\n }\n\n var mutator = mutators[config.autoReplaceSvg];\n return mutator || mutators.replace;\n}\n\nfunction createElementNS(tag) {\n return DOCUMENT.createElementNS('http://www.w3.org/2000/svg', tag);\n}\n\nfunction createElement(tag) {\n return DOCUMENT.createElement(tag);\n}\n\nfunction convertSVG(abstractObj) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _params$ceFn = params.ceFn,\n ceFn = _params$ceFn === void 0 ? abstractObj.tag === 'svg' ? createElementNS : createElement : _params$ceFn;\n\n if (typeof abstractObj === 'string') {\n return DOCUMENT.createTextNode(abstractObj);\n }\n\n var tag = ceFn(abstractObj.tag);\n Object.keys(abstractObj.attributes || []).forEach(function (key) {\n tag.setAttribute(key, abstractObj.attributes[key]);\n });\n var children = abstractObj.children || [];\n children.forEach(function (child) {\n tag.appendChild(convertSVG(child, {\n ceFn: ceFn\n }));\n });\n return tag;\n}\n\nfunction nodeAsComment(node) {\n var comment = \" \".concat(node.outerHTML, \" \");\n /* BEGIN.ATTRIBUTION */\n\n comment = \"\".concat(comment, \"Font Awesome fontawesome.com \");\n /* END.ATTRIBUTION */\n\n return comment;\n}\n\nvar mutators = {\n replace: function replace(mutation) {\n var node = mutation[0];\n\n if (node.parentNode) {\n mutation[1].forEach(function (_abstract) {\n node.parentNode.insertBefore(convertSVG(_abstract), node);\n });\n\n if (node.getAttribute(DATA_FA_I2SVG) === null && config.keepOriginalSource) {\n var comment = DOCUMENT.createComment(nodeAsComment(node));\n node.parentNode.replaceChild(comment, node);\n } else {\n node.remove();\n }\n }\n },\n nest: function nest(mutation) {\n var node = mutation[0];\n var _abstract2 = mutation[1]; // If we already have a replaced node we do not want to continue nesting within it.\n // Short-circuit to the standard replacement\n\n if (~classArray(node).indexOf(config.replacementClass)) {\n return mutators.replace(mutation);\n }\n\n var forSvg = new RegExp(\"\".concat(config.cssPrefix, \"-.*\"));\n delete _abstract2[0].attributes.id;\n\n if (_abstract2[0].attributes.class) {\n var splitClasses = _abstract2[0].attributes.class.split(' ').reduce(function (acc, cls) {\n if (cls === config.replacementClass || cls.match(forSvg)) {\n acc.toSvg.push(cls);\n } else {\n acc.toNode.push(cls);\n }\n\n return acc;\n }, {\n toNode: [],\n toSvg: []\n });\n\n _abstract2[0].attributes.class = splitClasses.toSvg.join(' ');\n\n if (splitClasses.toNode.length === 0) {\n node.removeAttribute('class');\n } else {\n node.setAttribute('class', splitClasses.toNode.join(' '));\n }\n }\n\n var newInnerHTML = _abstract2.map(function (a) {\n return toHtml(a);\n }).join('\\n');\n\n node.setAttribute(DATA_FA_I2SVG, '');\n node.innerHTML = newInnerHTML;\n }\n};\n\nfunction performOperationSync(op) {\n op();\n}\n\nfunction perform(mutations, callback) {\n var callbackFunction = typeof callback === 'function' ? callback : noop$2;\n\n if (mutations.length === 0) {\n callbackFunction();\n } else {\n var frame = performOperationSync;\n\n if (config.mutateApproach === MUTATION_APPROACH_ASYNC) {\n frame = WINDOW.requestAnimationFrame || performOperationSync;\n }\n\n frame(function () {\n var mutator = getMutator();\n var mark = perf.begin('mutate');\n mutations.map(mutator);\n mark();\n callbackFunction();\n });\n }\n}\nvar disabled = false;\nfunction disableObservation() {\n disabled = true;\n}\nfunction enableObservation() {\n disabled = false;\n}\nvar mo = null;\nfunction observe(options) {\n if (!MUTATION_OBSERVER) {\n return;\n }\n\n if (!config.observeMutations) {\n return;\n }\n\n var _options$treeCallback = options.treeCallback,\n treeCallback = _options$treeCallback === void 0 ? noop$2 : _options$treeCallback,\n _options$nodeCallback = options.nodeCallback,\n nodeCallback = _options$nodeCallback === void 0 ? noop$2 : _options$nodeCallback,\n _options$pseudoElemen = options.pseudoElementsCallback,\n pseudoElementsCallback = _options$pseudoElemen === void 0 ? noop$2 : _options$pseudoElemen,\n _options$observeMutat = options.observeMutationsRoot,\n observeMutationsRoot = _options$observeMutat === void 0 ? DOCUMENT : _options$observeMutat;\n mo = new MUTATION_OBSERVER(function (objects) {\n if (disabled) return;\n var defaultPrefix = getDefaultUsablePrefix();\n toArray(objects).forEach(function (mutationRecord) {\n if (mutationRecord.type === 'childList' && mutationRecord.addedNodes.length > 0 && !isWatched(mutationRecord.addedNodes[0])) {\n if (config.searchPseudoElements) {\n pseudoElementsCallback(mutationRecord.target);\n }\n\n treeCallback(mutationRecord.target);\n }\n\n if (mutationRecord.type === 'attributes' && mutationRecord.target.parentNode && config.searchPseudoElements) {\n pseudoElementsCallback(mutationRecord.target.parentNode);\n }\n\n if (mutationRecord.type === 'attributes' && isWatched(mutationRecord.target) && ~ATTRIBUTES_WATCHED_FOR_MUTATION.indexOf(mutationRecord.attributeName)) {\n if (mutationRecord.attributeName === 'class' && hasPrefixAndIcon(mutationRecord.target)) {\n var _getCanonicalIcon = getCanonicalIcon(classArray(mutationRecord.target)),\n prefix = _getCanonicalIcon.prefix,\n iconName = _getCanonicalIcon.iconName;\n\n mutationRecord.target.setAttribute(DATA_PREFIX, prefix || defaultPrefix);\n if (iconName) mutationRecord.target.setAttribute(DATA_ICON, iconName);\n } else if (hasBeenReplaced(mutationRecord.target)) {\n nodeCallback(mutationRecord.target);\n }\n }\n });\n });\n if (!IS_DOM) return;\n mo.observe(observeMutationsRoot, {\n childList: true,\n attributes: true,\n characterData: true,\n subtree: true\n });\n}\nfunction disconnect() {\n if (!mo) return;\n mo.disconnect();\n}\n\nfunction styleParser (node) {\n var style = node.getAttribute('style');\n var val = [];\n\n if (style) {\n val = style.split(';').reduce(function (acc, style) {\n var styles = style.split(':');\n var prop = styles[0];\n var value = styles.slice(1);\n\n if (prop && value.length > 0) {\n acc[prop] = value.join(':').trim();\n }\n\n return acc;\n }, {});\n }\n\n return val;\n}\n\nfunction classParser (node) {\n var existingPrefix = node.getAttribute('data-prefix');\n var existingIconName = node.getAttribute('data-icon');\n var innerText = node.innerText !== undefined ? node.innerText.trim() : '';\n var val = getCanonicalIcon(classArray(node));\n\n if (!val.prefix) {\n val.prefix = getDefaultUsablePrefix();\n }\n\n if (existingPrefix && existingIconName) {\n val.prefix = existingPrefix;\n val.iconName = existingIconName;\n }\n\n if (val.iconName && val.prefix) {\n return val;\n }\n\n if (val.prefix && innerText.length > 0) {\n val.iconName = byLigature(val.prefix, node.innerText) || byUnicode(val.prefix, toHex(node.innerText));\n }\n\n if (!val.iconName && config.autoFetchSvg && node.firstChild && node.firstChild.nodeType === Node.TEXT_NODE) {\n val.iconName = node.firstChild.data;\n }\n\n return val;\n}\n\nfunction attributesParser (node) {\n var extraAttributes = toArray(node.attributes).reduce(function (acc, attr) {\n if (acc.name !== 'class' && acc.name !== 'style') {\n acc[attr.name] = attr.value;\n }\n\n return acc;\n }, {});\n var title = node.getAttribute('title');\n var titleId = node.getAttribute('data-fa-title-id');\n\n if (config.autoA11y) {\n if (title) {\n extraAttributes['aria-labelledby'] = \"\".concat(config.replacementClass, \"-title-\").concat(titleId || nextUniqueId());\n } else {\n extraAttributes['aria-hidden'] = 'true';\n extraAttributes['focusable'] = 'false';\n }\n }\n\n return extraAttributes;\n}\n\nfunction blankMeta() {\n return {\n iconName: null,\n title: null,\n titleId: null,\n prefix: null,\n transform: meaninglessTransform,\n symbol: false,\n mask: {\n iconName: null,\n prefix: null,\n rest: []\n },\n maskId: null,\n extra: {\n classes: [],\n styles: {},\n attributes: {}\n }\n };\n}\nfunction parseMeta(node) {\n var parser = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n styleParser: true\n };\n\n var _classParser = classParser(node),\n iconName = _classParser.iconName,\n prefix = _classParser.prefix,\n extraClasses = _classParser.rest;\n\n var extraAttributes = attributesParser(node);\n var pluginMeta = chainHooks('parseNodeAttributes', {}, node);\n var extraStyles = parser.styleParser ? styleParser(node) : [];\n return _objectSpread2({\n iconName: iconName,\n title: node.getAttribute('title'),\n titleId: node.getAttribute('data-fa-title-id'),\n prefix: prefix,\n transform: meaninglessTransform,\n mask: {\n iconName: null,\n prefix: null,\n rest: []\n },\n maskId: null,\n symbol: false,\n extra: {\n classes: extraClasses,\n styles: extraStyles,\n attributes: extraAttributes\n }\n }, pluginMeta);\n}\n\nvar styles$2 = namespace.styles;\n\nfunction generateMutation(node) {\n var nodeMeta = config.autoReplaceSvg === 'nest' ? parseMeta(node, {\n styleParser: false\n }) : parseMeta(node);\n\n if (~nodeMeta.extra.classes.indexOf(LAYERS_TEXT_CLASSNAME)) {\n return callProvided('generateLayersText', node, nodeMeta);\n } else {\n return callProvided('generateSvgReplacementMutation', node, nodeMeta);\n }\n}\n\nvar knownPrefixes = new Set();\nFAMILIES.map(function (family) {\n knownPrefixes.add(\"fa-\".concat(family));\n});\nObject.keys(PREFIX_TO_STYLE[FAMILY_CLASSIC]).map(knownPrefixes.add.bind(knownPrefixes));\nObject.keys(PREFIX_TO_STYLE[FAMILY_SHARP]).map(knownPrefixes.add.bind(knownPrefixes));\nknownPrefixes = _toConsumableArray(knownPrefixes);\n\nfunction onTree(root) {\n var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n if (!IS_DOM) return Promise.resolve();\n var htmlClassList = DOCUMENT.documentElement.classList;\n\n var hclAdd = function hclAdd(suffix) {\n return htmlClassList.add(\"\".concat(HTML_CLASS_I2SVG_BASE_CLASS, \"-\").concat(suffix));\n };\n\n var hclRemove = function hclRemove(suffix) {\n return htmlClassList.remove(\"\".concat(HTML_CLASS_I2SVG_BASE_CLASS, \"-\").concat(suffix));\n };\n\n var prefixes = config.autoFetchSvg ? knownPrefixes : FAMILIES.map(function (f) {\n return \"fa-\".concat(f);\n }).concat(Object.keys(styles$2));\n\n if (!prefixes.includes('fa')) {\n prefixes.push('fa');\n }\n\n var prefixesDomQuery = [\".\".concat(LAYERS_TEXT_CLASSNAME, \":not([\").concat(DATA_FA_I2SVG, \"])\")].concat(prefixes.map(function (p) {\n return \".\".concat(p, \":not([\").concat(DATA_FA_I2SVG, \"])\");\n })).join(', ');\n\n if (prefixesDomQuery.length === 0) {\n return Promise.resolve();\n }\n\n var candidates = [];\n\n try {\n candidates = toArray(root.querySelectorAll(prefixesDomQuery));\n } catch (e) {// noop\n }\n\n if (candidates.length > 0) {\n hclAdd('pending');\n hclRemove('complete');\n } else {\n return Promise.resolve();\n }\n\n var mark = perf.begin('onTree');\n var mutations = candidates.reduce(function (acc, node) {\n try {\n var mutation = generateMutation(node);\n\n if (mutation) {\n acc.push(mutation);\n }\n } catch (e) {\n if (!PRODUCTION) {\n if (e.name === 'MissingIcon') {\n console.error(e);\n }\n }\n }\n\n return acc;\n }, []);\n return new Promise(function (resolve, reject) {\n Promise.all(mutations).then(function (resolvedMutations) {\n perform(resolvedMutations, function () {\n hclAdd('active');\n hclAdd('complete');\n hclRemove('pending');\n if (typeof callback === 'function') callback();\n mark();\n resolve();\n });\n }).catch(function (e) {\n mark();\n reject(e);\n });\n });\n}\n\nfunction onNode(node) {\n var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n generateMutation(node).then(function (mutation) {\n if (mutation) {\n perform([mutation], callback);\n }\n });\n}\n\nfunction resolveIcons(next) {\n return function (maybeIconDefinition) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var iconDefinition = (maybeIconDefinition || {}).icon ? maybeIconDefinition : findIconDefinition(maybeIconDefinition || {});\n var mask = params.mask;\n\n if (mask) {\n mask = (mask || {}).icon ? mask : findIconDefinition(mask || {});\n }\n\n return next(iconDefinition, _objectSpread2(_objectSpread2({}, params), {}, {\n mask: mask\n }));\n };\n}\n\nvar render = function render(iconDefinition) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _params$transform = params.transform,\n transform = _params$transform === void 0 ? meaninglessTransform : _params$transform,\n _params$symbol = params.symbol,\n symbol = _params$symbol === void 0 ? false : _params$symbol,\n _params$mask = params.mask,\n mask = _params$mask === void 0 ? null : _params$mask,\n _params$maskId = params.maskId,\n maskId = _params$maskId === void 0 ? null : _params$maskId,\n _params$title = params.title,\n title = _params$title === void 0 ? null : _params$title,\n _params$titleId = params.titleId,\n titleId = _params$titleId === void 0 ? null : _params$titleId,\n _params$classes = params.classes,\n classes = _params$classes === void 0 ? [] : _params$classes,\n _params$attributes = params.attributes,\n attributes = _params$attributes === void 0 ? {} : _params$attributes,\n _params$styles = params.styles,\n styles = _params$styles === void 0 ? {} : _params$styles;\n if (!iconDefinition) return;\n var prefix = iconDefinition.prefix,\n iconName = iconDefinition.iconName,\n icon = iconDefinition.icon;\n return domVariants(_objectSpread2({\n type: 'icon'\n }, iconDefinition), function () {\n callHooks('beforeDOMElementCreation', {\n iconDefinition: iconDefinition,\n params: params\n });\n\n if (config.autoA11y) {\n if (title) {\n attributes['aria-labelledby'] = \"\".concat(config.replacementClass, \"-title-\").concat(titleId || nextUniqueId());\n } else {\n attributes['aria-hidden'] = 'true';\n attributes['focusable'] = 'false';\n }\n }\n\n return makeInlineSvgAbstract({\n icons: {\n main: asFoundIcon(icon),\n mask: mask ? asFoundIcon(mask.icon) : {\n found: false,\n width: null,\n height: null,\n icon: {}\n }\n },\n prefix: prefix,\n iconName: iconName,\n transform: _objectSpread2(_objectSpread2({}, meaninglessTransform), transform),\n symbol: symbol,\n title: title,\n maskId: maskId,\n titleId: titleId,\n extra: {\n attributes: attributes,\n styles: styles,\n classes: classes\n }\n });\n });\n};\nvar ReplaceElements = {\n mixout: function mixout() {\n return {\n icon: resolveIcons(render)\n };\n },\n hooks: function hooks() {\n return {\n mutationObserverCallbacks: function mutationObserverCallbacks(accumulator) {\n accumulator.treeCallback = onTree;\n accumulator.nodeCallback = onNode;\n return accumulator;\n }\n };\n },\n provides: function provides(providers$$1) {\n providers$$1.i2svg = function (params) {\n var _params$node = params.node,\n node = _params$node === void 0 ? DOCUMENT : _params$node,\n _params$callback = params.callback,\n callback = _params$callback === void 0 ? function () {} : _params$callback;\n return onTree(node, callback);\n };\n\n providers$$1.generateSvgReplacementMutation = function (node, nodeMeta) {\n var iconName = nodeMeta.iconName,\n title = nodeMeta.title,\n titleId = nodeMeta.titleId,\n prefix = nodeMeta.prefix,\n transform = nodeMeta.transform,\n symbol = nodeMeta.symbol,\n mask = nodeMeta.mask,\n maskId = nodeMeta.maskId,\n extra = nodeMeta.extra;\n return new Promise(function (resolve, reject) {\n Promise.all([findIcon(iconName, prefix), mask.iconName ? findIcon(mask.iconName, mask.prefix) : Promise.resolve({\n found: false,\n width: 512,\n height: 512,\n icon: {}\n })]).then(function (_ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n main = _ref2[0],\n mask = _ref2[1];\n\n resolve([node, makeInlineSvgAbstract({\n icons: {\n main: main,\n mask: mask\n },\n prefix: prefix,\n iconName: iconName,\n transform: transform,\n symbol: symbol,\n maskId: maskId,\n title: title,\n titleId: titleId,\n extra: extra,\n watchable: true\n })]);\n }).catch(reject);\n });\n };\n\n providers$$1.generateAbstractIcon = function (_ref3) {\n var children = _ref3.children,\n attributes = _ref3.attributes,\n main = _ref3.main,\n transform = _ref3.transform,\n styles = _ref3.styles;\n var styleString = joinStyles(styles);\n\n if (styleString.length > 0) {\n attributes['style'] = styleString;\n }\n\n var nextChild;\n\n if (transformIsMeaningful(transform)) {\n nextChild = callProvided('generateAbstractTransformGrouping', {\n main: main,\n transform: transform,\n containerWidth: main.width,\n iconWidth: main.width\n });\n }\n\n children.push(nextChild || main.icon);\n return {\n children: children,\n attributes: attributes\n };\n };\n }\n};\n\nvar Layers = {\n mixout: function mixout() {\n return {\n layer: function layer(assembler) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _params$classes = params.classes,\n classes = _params$classes === void 0 ? [] : _params$classes;\n return domVariants({\n type: 'layer'\n }, function () {\n callHooks('beforeDOMElementCreation', {\n assembler: assembler,\n params: params\n });\n var children = [];\n assembler(function (args) {\n Array.isArray(args) ? args.map(function (a) {\n children = children.concat(a.abstract);\n }) : children = children.concat(args.abstract);\n });\n return [{\n tag: 'span',\n attributes: {\n class: [\"\".concat(config.cssPrefix, \"-layers\")].concat(_toConsumableArray(classes)).join(' ')\n },\n children: children\n }];\n });\n }\n };\n }\n};\n\nvar LayersCounter = {\n mixout: function mixout() {\n return {\n counter: function counter(content) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _params$title = params.title,\n title = _params$title === void 0 ? null : _params$title,\n _params$classes = params.classes,\n classes = _params$classes === void 0 ? [] : _params$classes,\n _params$attributes = params.attributes,\n attributes = _params$attributes === void 0 ? {} : _params$attributes,\n _params$styles = params.styles,\n styles = _params$styles === void 0 ? {} : _params$styles;\n return domVariants({\n type: 'counter',\n content: content\n }, function () {\n callHooks('beforeDOMElementCreation', {\n content: content,\n params: params\n });\n return makeLayersCounterAbstract({\n content: content.toString(),\n title: title,\n extra: {\n attributes: attributes,\n styles: styles,\n classes: [\"\".concat(config.cssPrefix, \"-layers-counter\")].concat(_toConsumableArray(classes))\n }\n });\n });\n }\n };\n }\n};\n\nvar LayersText = {\n mixout: function mixout() {\n return {\n text: function text(content) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var _params$transform = params.transform,\n transform = _params$transform === void 0 ? meaninglessTransform : _params$transform,\n _params$title = params.title,\n title = _params$title === void 0 ? null : _params$title,\n _params$classes = params.classes,\n classes = _params$classes === void 0 ? [] : _params$classes,\n _params$attributes = params.attributes,\n attributes = _params$attributes === void 0 ? {} : _params$attributes,\n _params$styles = params.styles,\n styles = _params$styles === void 0 ? {} : _params$styles;\n return domVariants({\n type: 'text',\n content: content\n }, function () {\n callHooks('beforeDOMElementCreation', {\n content: content,\n params: params\n });\n return makeLayersTextAbstract({\n content: content,\n transform: _objectSpread2(_objectSpread2({}, meaninglessTransform), transform),\n title: title,\n extra: {\n attributes: attributes,\n styles: styles,\n classes: [\"\".concat(config.cssPrefix, \"-layers-text\")].concat(_toConsumableArray(classes))\n }\n });\n });\n }\n };\n },\n provides: function provides(providers$$1) {\n providers$$1.generateLayersText = function (node, nodeMeta) {\n var title = nodeMeta.title,\n transform = nodeMeta.transform,\n extra = nodeMeta.extra;\n var width = null;\n var height = null;\n\n if (IS_IE) {\n var computedFontSize = parseInt(getComputedStyle(node).fontSize, 10);\n var boundingClientRect = node.getBoundingClientRect();\n width = boundingClientRect.width / computedFontSize;\n height = boundingClientRect.height / computedFontSize;\n }\n\n if (config.autoA11y && !title) {\n extra.attributes['aria-hidden'] = 'true';\n }\n\n return Promise.resolve([node, makeLayersTextAbstract({\n content: node.innerHTML,\n width: width,\n height: height,\n transform: transform,\n title: title,\n extra: extra,\n watchable: true\n })]);\n };\n }\n};\n\nvar CLEAN_CONTENT_PATTERN = new RegExp(\"\\\"\", 'ug');\nvar SECONDARY_UNICODE_RANGE = [1105920, 1112319];\nfunction hexValueFromContent(content) {\n var cleaned = content.replace(CLEAN_CONTENT_PATTERN, '');\n var codePoint = codePointAt(cleaned, 0);\n var isPrependTen = codePoint >= SECONDARY_UNICODE_RANGE[0] && codePoint <= SECONDARY_UNICODE_RANGE[1];\n var isDoubled = cleaned.length === 2 ? cleaned[0] === cleaned[1] : false;\n return {\n value: isDoubled ? toHex(cleaned[0]) : toHex(cleaned),\n isSecondary: isPrependTen || isDoubled\n };\n}\n\nfunction replaceForPosition(node, position) {\n var pendingAttribute = \"\".concat(DATA_FA_PSEUDO_ELEMENT_PENDING).concat(position.replace(':', '-'));\n return new Promise(function (resolve, reject) {\n if (node.getAttribute(pendingAttribute) !== null) {\n // This node is already being processed\n return resolve();\n }\n\n var children = toArray(node.children);\n var alreadyProcessedPseudoElement = children.filter(function (c) {\n return c.getAttribute(DATA_FA_PSEUDO_ELEMENT) === position;\n })[0];\n var styles = WINDOW.getComputedStyle(node, position);\n var fontFamily = styles.getPropertyValue('font-family').match(FONT_FAMILY_PATTERN);\n var fontWeight = styles.getPropertyValue('font-weight');\n var content = styles.getPropertyValue('content');\n\n if (alreadyProcessedPseudoElement && !fontFamily) {\n // If we've already processed it but the current computed style does not result in a font-family,\n // that probably means that a class name that was previously present to make the icon has been\n // removed. So we now should delete the icon.\n node.removeChild(alreadyProcessedPseudoElement);\n return resolve();\n } else if (fontFamily && content !== 'none' && content !== '') {\n var _content = styles.getPropertyValue('content');\n\n var family = ~['Sharp'].indexOf(fontFamily[2]) ? FAMILY_SHARP : FAMILY_CLASSIC;\n var prefix = ~['Solid', 'Regular', 'Light', 'Thin', 'Duotone', 'Brands', 'Kit'].indexOf(fontFamily[2]) ? STYLE_TO_PREFIX[family][fontFamily[2].toLowerCase()] : FONT_WEIGHT_TO_PREFIX[family][fontWeight];\n\n var _hexValueFromContent = hexValueFromContent(_content),\n hexValue = _hexValueFromContent.value,\n isSecondary = _hexValueFromContent.isSecondary;\n\n var isV4 = fontFamily[0].startsWith('FontAwesome');\n var iconName = byUnicode(prefix, hexValue);\n var iconIdentifier = iconName;\n\n if (isV4) {\n var iconName4 = byOldUnicode(hexValue);\n\n if (iconName4.iconName && iconName4.prefix) {\n iconName = iconName4.iconName;\n prefix = iconName4.prefix;\n }\n } // Only convert the pseudo element in this ::before/::after position into an icon if we haven't\n // already done so with the same prefix and iconName\n\n\n if (iconName && !isSecondary && (!alreadyProcessedPseudoElement || alreadyProcessedPseudoElement.getAttribute(DATA_PREFIX) !== prefix || alreadyProcessedPseudoElement.getAttribute(DATA_ICON) !== iconIdentifier)) {\n node.setAttribute(pendingAttribute, iconIdentifier);\n\n if (alreadyProcessedPseudoElement) {\n // Delete the old one, since we're replacing it with a new one\n node.removeChild(alreadyProcessedPseudoElement);\n }\n\n var meta = blankMeta();\n var extra = meta.extra;\n extra.attributes[DATA_FA_PSEUDO_ELEMENT] = position;\n findIcon(iconName, prefix).then(function (main) {\n var _abstract = makeInlineSvgAbstract(_objectSpread2(_objectSpread2({}, meta), {}, {\n icons: {\n main: main,\n mask: emptyCanonicalIcon()\n },\n prefix: prefix,\n iconName: iconIdentifier,\n extra: extra,\n watchable: true\n }));\n\n var element = DOCUMENT.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\n if (position === '::before') {\n node.insertBefore(element, node.firstChild);\n } else {\n node.appendChild(element);\n }\n\n element.outerHTML = _abstract.map(function (a) {\n return toHtml(a);\n }).join('\\n');\n node.removeAttribute(pendingAttribute);\n resolve();\n }).catch(reject);\n } else {\n resolve();\n }\n } else {\n resolve();\n }\n });\n}\n\nfunction replace(node) {\n return Promise.all([replaceForPosition(node, '::before'), replaceForPosition(node, '::after')]);\n}\n\nfunction processable(node) {\n return node.parentNode !== document.head && !~TAGNAMES_TO_SKIP_FOR_PSEUDOELEMENTS.indexOf(node.tagName.toUpperCase()) && !node.getAttribute(DATA_FA_PSEUDO_ELEMENT) && (!node.parentNode || node.parentNode.tagName !== 'svg');\n}\n\nfunction searchPseudoElements(root) {\n if (!IS_DOM) return;\n return new Promise(function (resolve, reject) {\n var operations = toArray(root.querySelectorAll('*')).filter(processable).map(replace);\n var end = perf.begin('searchPseudoElements');\n disableObservation();\n Promise.all(operations).then(function () {\n end();\n enableObservation();\n resolve();\n }).catch(function () {\n end();\n enableObservation();\n reject();\n });\n });\n}\n\nvar PseudoElements = {\n hooks: function hooks() {\n return {\n mutationObserverCallbacks: function mutationObserverCallbacks(accumulator) {\n accumulator.pseudoElementsCallback = searchPseudoElements;\n return accumulator;\n }\n };\n },\n provides: function provides(providers$$1) {\n providers$$1.pseudoElements2svg = function (params) {\n var _params$node = params.node,\n node = _params$node === void 0 ? DOCUMENT : _params$node;\n\n if (config.searchPseudoElements) {\n searchPseudoElements(node);\n }\n };\n }\n};\n\nvar _unwatched = false;\nvar MutationObserver$1 = {\n mixout: function mixout() {\n return {\n dom: {\n unwatch: function unwatch() {\n disableObservation();\n _unwatched = true;\n }\n }\n };\n },\n hooks: function hooks() {\n return {\n bootstrap: function bootstrap() {\n observe(chainHooks('mutationObserverCallbacks', {}));\n },\n noAuto: function noAuto() {\n disconnect();\n },\n watch: function watch(params) {\n var observeMutationsRoot = params.observeMutationsRoot;\n\n if (_unwatched) {\n enableObservation();\n } else {\n observe(chainHooks('mutationObserverCallbacks', {\n observeMutationsRoot: observeMutationsRoot\n }));\n }\n }\n };\n }\n};\n\nvar parseTransformString = function parseTransformString(transformString) {\n var transform = {\n size: 16,\n x: 0,\n y: 0,\n flipX: false,\n flipY: false,\n rotate: 0\n };\n return transformString.toLowerCase().split(' ').reduce(function (acc, n) {\n var parts = n.toLowerCase().split('-');\n var first = parts[0];\n var rest = parts.slice(1).join('-');\n\n if (first && rest === 'h') {\n acc.flipX = true;\n return acc;\n }\n\n if (first && rest === 'v') {\n acc.flipY = true;\n return acc;\n }\n\n rest = parseFloat(rest);\n\n if (isNaN(rest)) {\n return acc;\n }\n\n switch (first) {\n case 'grow':\n acc.size = acc.size + rest;\n break;\n\n case 'shrink':\n acc.size = acc.size - rest;\n break;\n\n case 'left':\n acc.x = acc.x - rest;\n break;\n\n case 'right':\n acc.x = acc.x + rest;\n break;\n\n case 'up':\n acc.y = acc.y - rest;\n break;\n\n case 'down':\n acc.y = acc.y + rest;\n break;\n\n case 'rotate':\n acc.rotate = acc.rotate + rest;\n break;\n }\n\n return acc;\n }, transform);\n};\nvar PowerTransforms = {\n mixout: function mixout() {\n return {\n parse: {\n transform: function transform(transformString) {\n return parseTransformString(transformString);\n }\n }\n };\n },\n hooks: function hooks() {\n return {\n parseNodeAttributes: function parseNodeAttributes(accumulator, node) {\n var transformString = node.getAttribute('data-fa-transform');\n\n if (transformString) {\n accumulator.transform = parseTransformString(transformString);\n }\n\n return accumulator;\n }\n };\n },\n provides: function provides(providers) {\n providers.generateAbstractTransformGrouping = function (_ref) {\n var main = _ref.main,\n transform = _ref.transform,\n containerWidth = _ref.containerWidth,\n iconWidth = _ref.iconWidth;\n var outer = {\n transform: \"translate(\".concat(containerWidth / 2, \" 256)\")\n };\n var innerTranslate = \"translate(\".concat(transform.x * 32, \", \").concat(transform.y * 32, \") \");\n var innerScale = \"scale(\".concat(transform.size / 16 * (transform.flipX ? -1 : 1), \", \").concat(transform.size / 16 * (transform.flipY ? -1 : 1), \") \");\n var innerRotate = \"rotate(\".concat(transform.rotate, \" 0 0)\");\n var inner = {\n transform: \"\".concat(innerTranslate, \" \").concat(innerScale, \" \").concat(innerRotate)\n };\n var path = {\n transform: \"translate(\".concat(iconWidth / 2 * -1, \" -256)\")\n };\n var operations = {\n outer: outer,\n inner: inner,\n path: path\n };\n return {\n tag: 'g',\n attributes: _objectSpread2({}, operations.outer),\n children: [{\n tag: 'g',\n attributes: _objectSpread2({}, operations.inner),\n children: [{\n tag: main.icon.tag,\n children: main.icon.children,\n attributes: _objectSpread2(_objectSpread2({}, main.icon.attributes), operations.path)\n }]\n }]\n };\n };\n }\n};\n\nvar ALL_SPACE = {\n x: 0,\n y: 0,\n width: '100%',\n height: '100%'\n};\n\nfunction fillBlack(_abstract) {\n var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\n if (_abstract.attributes && (_abstract.attributes.fill || force)) {\n _abstract.attributes.fill = 'black';\n }\n\n return _abstract;\n}\n\nfunction deGroup(_abstract2) {\n if (_abstract2.tag === 'g') {\n return _abstract2.children;\n } else {\n return [_abstract2];\n }\n}\n\nvar Masks = {\n hooks: function hooks() {\n return {\n parseNodeAttributes: function parseNodeAttributes(accumulator, node) {\n var maskData = node.getAttribute('data-fa-mask');\n var mask = !maskData ? emptyCanonicalIcon() : getCanonicalIcon(maskData.split(' ').map(function (i) {\n return i.trim();\n }));\n\n if (!mask.prefix) {\n mask.prefix = getDefaultUsablePrefix();\n }\n\n accumulator.mask = mask;\n accumulator.maskId = node.getAttribute('data-fa-mask-id');\n return accumulator;\n }\n };\n },\n provides: function provides(providers) {\n providers.generateAbstractMask = function (_ref) {\n var children = _ref.children,\n attributes = _ref.attributes,\n main = _ref.main,\n mask = _ref.mask,\n explicitMaskId = _ref.maskId,\n transform = _ref.transform;\n var mainWidth = main.width,\n mainPath = main.icon;\n var maskWidth = mask.width,\n maskPath = mask.icon;\n var trans = transformForSvg({\n transform: transform,\n containerWidth: maskWidth,\n iconWidth: mainWidth\n });\n var maskRect = {\n tag: 'rect',\n attributes: _objectSpread2(_objectSpread2({}, ALL_SPACE), {}, {\n fill: 'white'\n })\n };\n var maskInnerGroupChildrenMixin = mainPath.children ? {\n children: mainPath.children.map(fillBlack)\n } : {};\n var maskInnerGroup = {\n tag: 'g',\n attributes: _objectSpread2({}, trans.inner),\n children: [fillBlack(_objectSpread2({\n tag: mainPath.tag,\n attributes: _objectSpread2(_objectSpread2({}, mainPath.attributes), trans.path)\n }, maskInnerGroupChildrenMixin))]\n };\n var maskOuterGroup = {\n tag: 'g',\n attributes: _objectSpread2({}, trans.outer),\n children: [maskInnerGroup]\n };\n var maskId = \"mask-\".concat(explicitMaskId || nextUniqueId());\n var clipId = \"clip-\".concat(explicitMaskId || nextUniqueId());\n var maskTag = {\n tag: 'mask',\n attributes: _objectSpread2(_objectSpread2({}, ALL_SPACE), {}, {\n id: maskId,\n maskUnits: 'userSpaceOnUse',\n maskContentUnits: 'userSpaceOnUse'\n }),\n children: [maskRect, maskOuterGroup]\n };\n var defs = {\n tag: 'defs',\n children: [{\n tag: 'clipPath',\n attributes: {\n id: clipId\n },\n children: deGroup(maskPath)\n }, maskTag]\n };\n children.push(defs, {\n tag: 'rect',\n attributes: _objectSpread2({\n fill: 'currentColor',\n 'clip-path': \"url(#\".concat(clipId, \")\"),\n mask: \"url(#\".concat(maskId, \")\")\n }, ALL_SPACE)\n });\n return {\n children: children,\n attributes: attributes\n };\n };\n }\n};\n\nvar MissingIconIndicator = {\n provides: function provides(providers) {\n var reduceMotion = false;\n\n if (WINDOW.matchMedia) {\n reduceMotion = WINDOW.matchMedia('(prefers-reduced-motion: reduce)').matches;\n }\n\n providers.missingIconAbstract = function () {\n var gChildren = [];\n var FILL = {\n fill: 'currentColor'\n };\n var ANIMATION_BASE = {\n attributeType: 'XML',\n repeatCount: 'indefinite',\n dur: '2s'\n }; // Ring\n\n gChildren.push({\n tag: 'path',\n attributes: _objectSpread2(_objectSpread2({}, FILL), {}, {\n d: 'M156.5,447.7l-12.6,29.5c-18.7-9.5-35.9-21.2-51.5-34.9l22.7-22.7C127.6,430.5,141.5,440,156.5,447.7z M40.6,272H8.5 c1.4,21.2,5.4,41.7,11.7,61.1L50,321.2C45.1,305.5,41.8,289,40.6,272z M40.6,240c1.4-18.8,5.2-37,11.1-54.1l-29.5-12.6 C14.7,194.3,10,216.7,8.5,240H40.6z M64.3,156.5c7.8-14.9,17.2-28.8,28.1-41.5L69.7,92.3c-13.7,15.6-25.5,32.8-34.9,51.5 L64.3,156.5z M397,419.6c-13.9,12-29.4,22.3-46.1,30.4l11.9,29.8c20.7-9.9,39.8-22.6,56.9-37.6L397,419.6z M115,92.4 c13.9-12,29.4-22.3,46.1-30.4l-11.9-29.8c-20.7,9.9-39.8,22.6-56.8,37.6L115,92.4z M447.7,355.5c-7.8,14.9-17.2,28.8-28.1,41.5 l22.7,22.7c13.7-15.6,25.5-32.9,34.9-51.5L447.7,355.5z M471.4,272c-1.4,18.8-5.2,37-11.1,54.1l29.5,12.6 c7.5-21.1,12.2-43.5,13.6-66.8H471.4z M321.2,462c-15.7,5-32.2,8.2-49.2,9.4v32.1c21.2-1.4,41.7-5.4,61.1-11.7L321.2,462z M240,471.4c-18.8-1.4-37-5.2-54.1-11.1l-12.6,29.5c21.1,7.5,43.5,12.2,66.8,13.6V471.4z M462,190.8c5,15.7,8.2,32.2,9.4,49.2h32.1 c-1.4-21.2-5.4-41.7-11.7-61.1L462,190.8z M92.4,397c-12-13.9-22.3-29.4-30.4-46.1l-29.8,11.9c9.9,20.7,22.6,39.8,37.6,56.9 L92.4,397z M272,40.6c18.8,1.4,36.9,5.2,54.1,11.1l12.6-29.5C317.7,14.7,295.3,10,272,8.5V40.6z M190.8,50 c15.7-5,32.2-8.2,49.2-9.4V8.5c-21.2,1.4-41.7,5.4-61.1,11.7L190.8,50z M442.3,92.3L419.6,115c12,13.9,22.3,29.4,30.5,46.1 l29.8-11.9C470,128.5,457.3,109.4,442.3,92.3z M397,92.4l22.7-22.7c-15.6-13.7-32.8-25.5-51.5-34.9l-12.6,29.5 C370.4,72.1,384.4,81.5,397,92.4z'\n })\n });\n\n var OPACITY_ANIMATE = _objectSpread2(_objectSpread2({}, ANIMATION_BASE), {}, {\n attributeName: 'opacity'\n });\n\n var dot = {\n tag: 'circle',\n attributes: _objectSpread2(_objectSpread2({}, FILL), {}, {\n cx: '256',\n cy: '364',\n r: '28'\n }),\n children: []\n };\n\n if (!reduceMotion) {\n dot.children.push({\n tag: 'animate',\n attributes: _objectSpread2(_objectSpread2({}, ANIMATION_BASE), {}, {\n attributeName: 'r',\n values: '28;14;28;28;14;28;'\n })\n }, {\n tag: 'animate',\n attributes: _objectSpread2(_objectSpread2({}, OPACITY_ANIMATE), {}, {\n values: '1;0;1;1;0;1;'\n })\n });\n }\n\n gChildren.push(dot);\n gChildren.push({\n tag: 'path',\n attributes: _objectSpread2(_objectSpread2({}, FILL), {}, {\n opacity: '1',\n d: 'M263.7,312h-16c-6.6,0-12-5.4-12-12c0-71,77.4-63.9,77.4-107.8c0-20-17.8-40.2-57.4-40.2c-29.1,0-44.3,9.6-59.2,28.7 c-3.9,5-11.1,6-16.2,2.4l-13.1-9.2c-5.6-3.9-6.9-11.8-2.6-17.2c21.2-27.2,46.4-44.7,91.2-44.7c52.3,0,97.4,29.8,97.4,80.2 c0,67.6-77.4,63.5-77.4,107.8C275.7,306.6,270.3,312,263.7,312z'\n }),\n children: reduceMotion ? [] : [{\n tag: 'animate',\n attributes: _objectSpread2(_objectSpread2({}, OPACITY_ANIMATE), {}, {\n values: '1;0;0;0;0;1;'\n })\n }]\n });\n\n if (!reduceMotion) {\n // Exclamation\n gChildren.push({\n tag: 'path',\n attributes: _objectSpread2(_objectSpread2({}, FILL), {}, {\n opacity: '0',\n d: 'M232.5,134.5l7,168c0.3,6.4,5.6,11.5,12,11.5h9c6.4,0,11.7-5.1,12-11.5l7-168c0.3-6.8-5.2-12.5-12-12.5h-23 C237.7,122,232.2,127.7,232.5,134.5z'\n }),\n children: [{\n tag: 'animate',\n attributes: _objectSpread2(_objectSpread2({}, OPACITY_ANIMATE), {}, {\n values: '0;0;1;1;0;0;'\n })\n }]\n });\n }\n\n return {\n tag: 'g',\n attributes: {\n 'class': 'missing'\n },\n children: gChildren\n };\n };\n }\n};\n\nvar SvgSymbols = {\n hooks: function hooks() {\n return {\n parseNodeAttributes: function parseNodeAttributes(accumulator, node) {\n var symbolData = node.getAttribute('data-fa-symbol');\n var symbol = symbolData === null ? false : symbolData === '' ? true : symbolData;\n accumulator['symbol'] = symbol;\n return accumulator;\n }\n };\n }\n};\n\nvar plugins = [InjectCSS, ReplaceElements, Layers, LayersCounter, LayersText, PseudoElements, MutationObserver$1, PowerTransforms, Masks, MissingIconIndicator, SvgSymbols];\n\nregisterPlugins(plugins, {\n mixoutsTo: api\n});\nvar noAuto$1 = api.noAuto;\nvar config$1 = api.config;\nvar library$1 = api.library;\nvar dom$1 = api.dom;\nvar parse$1 = api.parse;\nvar findIconDefinition$1 = api.findIconDefinition;\nvar toHtml$1 = api.toHtml;\nvar icon = api.icon;\nvar layer = api.layer;\nvar text = api.text;\nvar counter = api.counter;\n\nexport { noAuto$1 as noAuto, config$1 as config, library$1 as library, dom$1 as dom, parse$1 as parse, findIconDefinition$1 as findIconDefinition, toHtml$1 as toHtml, icon, layer, text, counter, api };\n","import { parse, icon } from '@fortawesome/fontawesome-svg-core';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n enumerableOnly && (symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n })), keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = null != arguments[i] ? arguments[i] : {};\n i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n\n return target;\n}\n\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}\n\nfunction _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = _objectWithoutPropertiesLoose(source, excluded);\n\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\n\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\n\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\n// Get CSS class list from a props object\nfunction classList(props) {\n var _classes;\n\n var beat = props.beat,\n fade = props.fade,\n beatFade = props.beatFade,\n bounce = props.bounce,\n shake = props.shake,\n flash = props.flash,\n spin = props.spin,\n spinPulse = props.spinPulse,\n spinReverse = props.spinReverse,\n pulse = props.pulse,\n fixedWidth = props.fixedWidth,\n inverse = props.inverse,\n border = props.border,\n listItem = props.listItem,\n flip = props.flip,\n size = props.size,\n rotation = props.rotation,\n pull = props.pull; // map of CSS class names to properties\n\n var classes = (_classes = {\n 'fa-beat': beat,\n 'fa-fade': fade,\n 'fa-beat-fade': beatFade,\n 'fa-bounce': bounce,\n 'fa-shake': shake,\n 'fa-flash': flash,\n 'fa-spin': spin,\n 'fa-spin-reverse': spinReverse,\n 'fa-spin-pulse': spinPulse,\n 'fa-pulse': pulse,\n 'fa-fw': fixedWidth,\n 'fa-inverse': inverse,\n 'fa-border': border,\n 'fa-li': listItem,\n 'fa-flip': flip === true,\n 'fa-flip-horizontal': flip === 'horizontal' || flip === 'both',\n 'fa-flip-vertical': flip === 'vertical' || flip === 'both'\n }, _defineProperty(_classes, \"fa-\".concat(size), typeof size !== 'undefined' && size !== null), _defineProperty(_classes, \"fa-rotate-\".concat(rotation), typeof rotation !== 'undefined' && rotation !== null && rotation !== 0), _defineProperty(_classes, \"fa-pull-\".concat(pull), typeof pull !== 'undefined' && pull !== null), _defineProperty(_classes, 'fa-swap-opacity', props.swapOpacity), _classes); // map over all the keys in the classes object\n // return an array of the keys where the value for the key is not null\n\n return Object.keys(classes).map(function (key) {\n return classes[key] ? key : null;\n }).filter(function (key) {\n return key;\n });\n}\n\n// Camelize taken from humps\n// humps is copyright © 2012+ Dom Christie\n// Released under the MIT license.\n// Performant way to determine if object coerces to a number\nfunction _isNumerical(obj) {\n obj = obj - 0; // eslint-disable-next-line no-self-compare\n\n return obj === obj;\n}\n\nfunction camelize(string) {\n if (_isNumerical(string)) {\n return string;\n } // eslint-disable-next-line no-useless-escape\n\n\n string = string.replace(/[\\-_\\s]+(.)?/g, function (match, chr) {\n return chr ? chr.toUpperCase() : '';\n }); // Ensure 1st char is always lowercase\n\n return string.substr(0, 1).toLowerCase() + string.substr(1);\n}\n\nvar _excluded = [\"style\"];\n\nfunction capitalize(val) {\n return val.charAt(0).toUpperCase() + val.slice(1);\n}\n\nfunction styleToObject(style) {\n return style.split(';').map(function (s) {\n return s.trim();\n }).filter(function (s) {\n return s;\n }).reduce(function (acc, pair) {\n var i = pair.indexOf(':');\n var prop = camelize(pair.slice(0, i));\n var value = pair.slice(i + 1).trim();\n prop.startsWith('webkit') ? acc[capitalize(prop)] = value : acc[prop] = value;\n return acc;\n }, {});\n}\n\nfunction convert(createElement, element) {\n var extraProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (typeof element === 'string') {\n return element;\n }\n\n var children = (element.children || []).map(function (child) {\n return convert(createElement, child);\n });\n /* eslint-disable dot-notation */\n\n var mixins = Object.keys(element.attributes || {}).reduce(function (acc, key) {\n var val = element.attributes[key];\n\n switch (key) {\n case 'class':\n acc.attrs['className'] = val;\n delete element.attributes['class'];\n break;\n\n case 'style':\n acc.attrs['style'] = styleToObject(val);\n break;\n\n default:\n if (key.indexOf('aria-') === 0 || key.indexOf('data-') === 0) {\n acc.attrs[key.toLowerCase()] = val;\n } else {\n acc.attrs[camelize(key)] = val;\n }\n\n }\n\n return acc;\n }, {\n attrs: {}\n });\n\n var _extraProps$style = extraProps.style,\n existingStyle = _extraProps$style === void 0 ? {} : _extraProps$style,\n remaining = _objectWithoutProperties(extraProps, _excluded);\n\n mixins.attrs['style'] = _objectSpread2(_objectSpread2({}, mixins.attrs['style']), existingStyle);\n /* eslint-enable */\n\n return createElement.apply(void 0, [element.tag, _objectSpread2(_objectSpread2({}, mixins.attrs), remaining)].concat(_toConsumableArray(children)));\n}\n\nvar PRODUCTION = false;\n\ntry {\n PRODUCTION = process.env.NODE_ENV === 'production';\n} catch (e) {}\n\nfunction log () {\n if (!PRODUCTION && console && typeof console.error === 'function') {\n var _console;\n\n (_console = console).error.apply(_console, arguments);\n }\n}\n\nfunction normalizeIconArgs(icon) {\n // this has everything that it needs to be rendered which means it was probably imported\n // directly from an icon svg package\n if (icon && _typeof(icon) === 'object' && icon.prefix && icon.iconName && icon.icon) {\n return icon;\n }\n\n if (parse.icon) {\n return parse.icon(icon);\n } // if the icon is null, there's nothing to do\n\n\n if (icon === null) {\n return null;\n } // if the icon is an object and has a prefix and an icon name, return it\n\n\n if (icon && _typeof(icon) === 'object' && icon.prefix && icon.iconName) {\n return icon;\n } // if it's an array with length of two\n\n\n if (Array.isArray(icon) && icon.length === 2) {\n // use the first item as prefix, second as icon name\n return {\n prefix: icon[0],\n iconName: icon[1]\n };\n } // if it's a string, use it as the icon name\n\n\n if (typeof icon === 'string') {\n return {\n prefix: 'fas',\n iconName: icon\n };\n }\n}\n\n// creates an object with a key of key\n// and a value of value\n// if certain conditions are met\nfunction objectWithKey(key, value) {\n // if the value is a non-empty array\n // or it's not an array but it is truthy\n // then create the object with the key and the value\n // if not, return an empty array\n return Array.isArray(value) && value.length > 0 || !Array.isArray(value) && value ? _defineProperty({}, key, value) : {};\n}\n\nvar FontAwesomeIcon = /*#__PURE__*/React.forwardRef(function (props, ref) {\n var iconArgs = props.icon,\n maskArgs = props.mask,\n symbol = props.symbol,\n className = props.className,\n title = props.title,\n titleId = props.titleId,\n maskId = props.maskId;\n var iconLookup = normalizeIconArgs(iconArgs);\n var classes = objectWithKey('classes', [].concat(_toConsumableArray(classList(props)), _toConsumableArray(className.split(' '))));\n var transform = objectWithKey('transform', typeof props.transform === 'string' ? parse.transform(props.transform) : props.transform);\n var mask = objectWithKey('mask', normalizeIconArgs(maskArgs));\n var renderedIcon = icon(iconLookup, _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, classes), transform), mask), {}, {\n symbol: symbol,\n title: title,\n titleId: titleId,\n maskId: maskId\n }));\n\n if (!renderedIcon) {\n log('Could not find icon', iconLookup);\n return null;\n }\n\n var abstract = renderedIcon.abstract;\n var extraProps = {\n ref: ref\n };\n Object.keys(props).forEach(function (key) {\n // eslint-disable-next-line no-prototype-builtins\n if (!FontAwesomeIcon.defaultProps.hasOwnProperty(key)) {\n extraProps[key] = props[key];\n }\n });\n return convertCurry(abstract[0], extraProps);\n});\nFontAwesomeIcon.displayName = 'FontAwesomeIcon';\nFontAwesomeIcon.propTypes = {\n beat: PropTypes.bool,\n border: PropTypes.bool,\n beatFade: PropTypes.bool,\n bounce: PropTypes.bool,\n className: PropTypes.string,\n fade: PropTypes.bool,\n flash: PropTypes.bool,\n mask: PropTypes.oneOfType([PropTypes.object, PropTypes.array, PropTypes.string]),\n maskId: PropTypes.string,\n fixedWidth: PropTypes.bool,\n inverse: PropTypes.bool,\n flip: PropTypes.oneOf([true, false, 'horizontal', 'vertical', 'both']),\n icon: PropTypes.oneOfType([PropTypes.object, PropTypes.array, PropTypes.string]),\n listItem: PropTypes.bool,\n pull: PropTypes.oneOf(['right', 'left']),\n pulse: PropTypes.bool,\n rotation: PropTypes.oneOf([0, 90, 180, 270]),\n shake: PropTypes.bool,\n size: PropTypes.oneOf(['2xs', 'xs', 'sm', 'lg', 'xl', '2xl', '1x', '2x', '3x', '4x', '5x', '6x', '7x', '8x', '9x', '10x']),\n spin: PropTypes.bool,\n spinPulse: PropTypes.bool,\n spinReverse: PropTypes.bool,\n symbol: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),\n title: PropTypes.string,\n titleId: PropTypes.string,\n transform: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),\n swapOpacity: PropTypes.bool\n};\nFontAwesomeIcon.defaultProps = {\n border: false,\n className: '',\n mask: null,\n maskId: null,\n fixedWidth: false,\n inverse: false,\n flip: false,\n icon: null,\n listItem: false,\n pull: null,\n pulse: false,\n rotation: null,\n size: null,\n spin: false,\n spinPulse: false,\n spinReverse: false,\n beat: false,\n fade: false,\n beatFade: false,\n bounce: false,\n shake: false,\n symbol: false,\n title: '',\n titleId: null,\n transform: null,\n swapOpacity: false\n};\nvar convertCurry = convert.bind(null, React.createElement);\n\nexport { FontAwesomeIcon };\n","/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1 /*#__PURE__*/React.forwardRef((p, ref) => /*#__PURE__*/_jsx(\"div\", {\n ...p,\n ref: ref,\n className: classNames(p.className, className)\n})));","/*!\n\tCopyright (c) 2018 Jed Watson.\n\tLicensed under the MIT License (MIT), see\n\thttp://jedwatson.github.io/classnames\n*/\n/* global define */\n\n(function () {\n\t'use strict';\n\n\tvar hasOwn = {}.hasOwnProperty;\n\tvar nativeCodeString = '[native code]';\n\n\tfunction classNames() {\n\t\tvar classes = [];\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tvar arg = arguments[i];\n\t\t\tif (!arg) continue;\n\n\t\t\tvar argType = typeof arg;\n\n\t\t\tif (argType === 'string' || argType === 'number') {\n\t\t\t\tclasses.push(arg);\n\t\t\t} else if (Array.isArray(arg)) {\n\t\t\t\tif (arg.length) {\n\t\t\t\t\tvar inner = classNames.apply(null, arg);\n\t\t\t\t\tif (inner) {\n\t\t\t\t\t\tclasses.push(inner);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (argType === 'object') {\n\t\t\t\tif (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {\n\t\t\t\t\tclasses.push(arg.toString());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfor (var key in arg) {\n\t\t\t\t\tif (hasOwn.call(arg, key) && arg[key]) {\n\t\t\t\t\t\tclasses.push(key);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn classes.join(' ');\n\t}\n\n\tif (typeof module !== 'undefined' && module.exports) {\n\t\tclassNames.default = classNames;\n\t\tmodule.exports = classNames;\n\t} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {\n\t\t// register as 'classnames', consistent with npm package name\n\t\tdefine('classnames', [], function () {\n\t\t\treturn classNames;\n\t\t});\n\t} else {\n\t\twindow.classNames = classNames;\n\t}\n}());\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.min.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n(function() {'use strict';var h;/** @license\n\n Copyright The Closure Library Authors.\n SPDX-License-Identifier: Apache-2.0\n*/\nfunction k(f,a){function c(){}c.prototype=a.prototype;f.D=a.prototype;f.prototype=new c;f.prototype.constructor=f;f.C=function(d,e,g){for(var b=Array(arguments.length-2),r=2;re;++e)d[e]=a.charCodeAt(c++)|a.charCodeAt(c++)<<8|a.charCodeAt(c++)<<16|a.charCodeAt(c++)<<24;else for(e=0;16>e;++e)d[e]=a[c++]|a[c++]<<8|a[c++]<<16|a[c++]<<24;a=f.g[0];c=f.g[1];e=f.g[2];var g=f.g[3];var b=a+(g^c&(e^g))+d[0]+3614090360&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[1]+3905402710&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[2]+606105819&4294967295;e=g+(b<<17&4294967295|b>>>15);\nb=c+(a^e&(g^a))+d[3]+3250441966&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[4]+4118548399&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[5]+1200080426&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[6]+2821735955&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[7]+4249261313&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[8]+1770035416&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[9]+2336552879&4294967295;g=a+(b<<12&4294967295|\nb>>>20);b=e+(c^g&(a^c))+d[10]+4294925233&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[11]+2304563134&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(g^c&(e^g))+d[12]+1804603682&4294967295;a=c+(b<<7&4294967295|b>>>25);b=g+(e^a&(c^e))+d[13]+4254626195&4294967295;g=a+(b<<12&4294967295|b>>>20);b=e+(c^g&(a^c))+d[14]+2792965006&4294967295;e=g+(b<<17&4294967295|b>>>15);b=c+(a^e&(g^a))+d[15]+1236535329&4294967295;c=e+(b<<22&4294967295|b>>>10);b=a+(e^g&(c^e))+d[1]+4129170786&4294967295;a=c+(b<<\n5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[6]+3225465664&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[11]+643717713&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[0]+3921069994&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[5]+3593408605&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[10]+38016083&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[15]+3634488961&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[4]+3889429448&4294967295;c=\ne+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[9]+568446438&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[14]+3275163606&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[3]+4107603335&4294967295;e=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[8]+1163531501&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(e^g&(c^e))+d[13]+2850285829&4294967295;a=c+(b<<5&4294967295|b>>>27);b=g+(c^e&(a^c))+d[2]+4243563512&4294967295;g=a+(b<<9&4294967295|b>>>23);b=e+(a^c&(g^a))+d[7]+1735328473&4294967295;\ne=g+(b<<14&4294967295|b>>>18);b=c+(g^a&(e^g))+d[12]+2368359562&4294967295;c=e+(b<<20&4294967295|b>>>12);b=a+(c^e^g)+d[5]+4294588738&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[8]+2272392833&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[11]+1839030562&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[14]+4259657740&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[1]+2763975236&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[4]+1272893353&4294967295;g=a+(b<<11&4294967295|\nb>>>21);b=e+(g^a^c)+d[7]+4139469664&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[10]+3200236656&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[13]+681279174&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[0]+3936430074&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[3]+3572445317&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[6]+76029189&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(c^e^g)+d[9]+3654602809&4294967295;a=c+(b<<4&4294967295|b>>>28);b=g+(a^c^e)+d[12]+\n3873151461&4294967295;g=a+(b<<11&4294967295|b>>>21);b=e+(g^a^c)+d[15]+530742520&4294967295;e=g+(b<<16&4294967295|b>>>16);b=c+(e^g^a)+d[2]+3299628645&4294967295;c=e+(b<<23&4294967295|b>>>9);b=a+(e^(c|~g))+d[0]+4096336452&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[7]+1126891415&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[14]+2878612391&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[5]+4237533241&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[12]+1700485571&\n4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[3]+2399980690&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[10]+4293915773&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[1]+2240044497&4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[8]+1873313359&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[15]+4264355552&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[6]+2734768916&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[13]+1309151649&\n4294967295;c=e+(b<<21&4294967295|b>>>11);b=a+(e^(c|~g))+d[4]+4149444226&4294967295;a=c+(b<<6&4294967295|b>>>26);b=g+(c^(a|~e))+d[11]+3174756917&4294967295;g=a+(b<<10&4294967295|b>>>22);b=e+(a^(g|~c))+d[2]+718787259&4294967295;e=g+(b<<15&4294967295|b>>>17);b=c+(g^(e|~a))+d[9]+3951481745&4294967295;f.g[0]=f.g[0]+a&4294967295;f.g[1]=f.g[1]+(e+(b<<21&4294967295|b>>>11))&4294967295;f.g[2]=f.g[2]+e&4294967295;f.g[3]=f.g[3]+g&4294967295}\nm.prototype.u=function(f,a){void 0===a&&(a=f.length);for(var c=a-this.blockSize,d=this.B,e=this.h,g=0;gthis.h?this.blockSize:2*this.blockSize)-this.h);f[0]=128;for(var a=1;aa;++a)for(var d=0;32>d;d+=8)f[c++]=this.g[a]>>>d&255;return f};function p(f,a){var c=q;return Object.prototype.hasOwnProperty.call(c,f)?c[f]:c[f]=a(f)};function t(f,a){this.h=a;for(var c=[],d=!0,e=f.length-1;0<=e;e--){var g=f[e]|0;d&&g==a||(c[e]=g,d=!1)}this.g=c}var q={};function u(f){return-128<=f&&128>f?p(f,function(a){return new t([a|0],0>a?-1:0)}):new t([f|0],0>f?-1:0)}function v(f){if(isNaN(f)||!isFinite(f))return w;if(0>f)return x(v(-f));for(var a=[],c=1,d=0;f>=c;d++)a[d]=f/c|0,c*=4294967296;return new t(a,0)}\nfunction y(f,a){if(0==f.length)throw Error(\"number format error: empty string\");a=a||10;if(2>a||36g?(g=v(Math.pow(a,g)),d=d.j(g).add(v(b))):(d=d.j(c),d=d.add(v(b)))}return d}var w=u(0),z=u(1),A=u(16777216);h=t.prototype;\nh.m=function(){if(B(this))return-x(this).m();for(var f=0,a=1,c=0;cf||36>>0).toString(f);c=e;if(C(c))return g+d;for(;6>g.length;)g=\"0\"+g;d=g+d}};\nh.i=function(f){return 0>f?0:f>>16)+(this.i(e)>>>16)+(f.i(e)>>>16);d=b>>>16;g&=65535;b&=65535;c[e]=b<<16|g}return new t(c,c[c.length-1]&-2147483648?-1:0)};function F(f,a){return f.add(x(a))}\nh.j=function(f){if(C(this)||C(f))return w;if(B(this))return B(f)?x(this).j(x(f)):x(x(this).j(f));if(B(f))return x(this.j(x(f)));if(0>this.l(A)&&0>f.l(A))return v(this.m()*f.m());for(var a=this.g.length+f.g.length,c=[],d=0;d<2*a;d++)c[d]=0;for(d=0;d>>16,b=this.i(d)&65535,r=f.i(e)>>>16,E=f.i(e)&65535;c[2*d+2*e]+=b*E;G(c,2*d+2*e);c[2*d+2*e+1]+=g*E;G(c,2*d+2*e+1);c[2*d+2*e+1]+=b*r;G(c,2*d+2*e+1);c[2*d+2*e+2]+=g*r;G(c,2*d+2*e+2)}for(d=0;d<\na;d++)c[d]=c[2*d+1]<<16|c[2*d];for(d=a;d<2*a;d++)c[d]=0;return new t(c,0)};function G(f,a){for(;(f[a]&65535)!=f[a];)f[a+1]+=f[a]>>>16,f[a]&=65535,a++}function H(f,a){this.g=f;this.h=a}\nfunction D(f,a){if(C(a))throw Error(\"division by zero\");if(C(f))return new H(w,w);if(B(f))return a=D(x(f),a),new H(x(a.g),x(a.h));if(B(a))return a=D(f,x(a)),new H(x(a.g),a.h);if(30=d.l(f);)c=I(c),d=I(d);var e=J(c,1),g=J(d,1);d=J(d,2);for(c=J(c,2);!C(d);){var b=g.add(d);0>=b.l(f)&&(e=e.add(c),g=b);d=J(d,1);c=J(c,1)}a=F(f,e.j(a));return new H(e,a)}for(e=w;0<=f.l(a);){c=Math.max(1,Math.floor(f.m()/\na.m()));d=Math.ceil(Math.log(c)/Math.LN2);d=48>=d?1:Math.pow(2,d-48);g=v(c);for(b=g.j(a);B(b)||0>>31;return new t(c,f.h)}function J(f,a){var c=a>>5;a%=32;for(var d=f.g.length-c,e=[],g=0;g>>a|f.i(g+c+1)<<32-a:f.i(g+c);return new t(e,f.h)};m.prototype.digest=m.prototype.v;m.prototype.reset=m.prototype.s;m.prototype.update=m.prototype.u;module.exports.Md5=m;t.prototype.add=t.prototype.add;t.prototype.multiply=t.prototype.j;t.prototype.modulo=t.prototype.A;t.prototype.compare=t.prototype.l;t.prototype.toNumber=t.prototype.m;t.prototype.toString=t.prototype.toString;t.prototype.getBits=t.prototype.i;t.fromNumber=v;t.fromString=y;module.exports.Integer=t;}).apply( typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {});\n","/** @license\nCopyright The Closure Library Authors.\nSPDX-License-Identifier: Apache-2.0\n*/\n(function() {'use strict';var h,aa=\"function\"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};function ba(a){a=[\"object\"==typeof globalThis&&globalThis,a,\"object\"==typeof window&&window,\"object\"==typeof self&&self,\"object\"==typeof global&&global];for(var b=0;b{throw a;},0)};function xa(){var a=za;let b=null;a.g&&(b=a.g,a.g=a.g.next,a.g||(a.h=null),b.next=null);return b}class Aa{constructor(){this.h=this.g=null}add(a,b){const c=Ba.get();c.set(a,b);this.h?this.h.next=c:this.g=c;this.h=c}}var Ba=new na(()=>new Ca,a=>a.reset());class Ca{constructor(){this.next=this.g=this.h=null}set(a,b){this.h=a;this.g=b;this.next=null}reset(){this.next=this.g=this.h=null}};let x,y=!1,za=new Aa,Ea=()=>{const a=k.Promise.resolve(void 0);x=()=>{a.then(Da)}};var Da=()=>{for(var a;a=xa();){try{a.h.call(a.g)}catch(c){wa(c)}var b=Ba;b.j(a);100>b.h&&(b.h++,a.next=b.g,b.g=a)}y=!1};function z(){this.s=this.s;this.C=this.C}z.prototype.s=!1;z.prototype.ma=function(){this.s||(this.s=!0,this.N())};z.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()};function A(a,b){this.type=a;this.g=this.target=b;this.defaultPrevented=!1}A.prototype.h=function(){this.defaultPrevented=!0};var Fa=function(){if(!k.addEventListener||!Object.defineProperty)return!1;var a=!1,b=Object.defineProperty({},\"passive\",{get:function(){a=!0}});try{const c=()=>{};k.addEventListener(\"test\",c,b);k.removeEventListener(\"test\",c,b)}catch(c){}return a}();function C(a,b){A.call(this,a?a.type:\"\");this.relatedTarget=this.g=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=0;this.key=\"\";this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.pointerId=0;this.pointerType=\"\";this.i=null;if(a){var c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.g=b;if(b=a.relatedTarget){if(pa){a:{try{oa(b.nodeName);var e=!0;break a}catch(f){}e=\n!1}e||(b=null)}}else\"mouseover\"==c?b=a.fromElement:\"mouseout\"==c&&(b=a.toElement);this.relatedTarget=b;d?(this.clientX=void 0!==d.clientX?d.clientX:d.pageX,this.clientY=void 0!==d.clientY?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.clientX=void 0!==a.clientX?a.clientX:a.pageX,this.clientY=void 0!==a.clientY?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.key=a.key||\"\";this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=\na.shiftKey;this.metaKey=a.metaKey;this.pointerId=a.pointerId||0;this.pointerType=\"string\"===typeof a.pointerType?a.pointerType:Ga[a.pointerType]||\"\";this.state=a.state;this.i=a;a.defaultPrevented&&C.aa.h.call(this)}}r(C,A);var Ga={2:\"touch\",3:\"pen\",4:\"mouse\"};C.prototype.h=function(){C.aa.h.call(this);var a=this.i;a.preventDefault?a.preventDefault():a.returnValue=!1};var D=\"closure_listenable_\"+(1E6*Math.random()|0);var Ha=0;function Ia(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.ha=e;this.key=++Ha;this.da=this.fa=!1}function Ja(a){a.da=!0;a.listener=null;a.proxy=null;a.src=null;a.ha=null};function Ka(a){this.src=a;this.g={};this.h=0}Ka.prototype.add=function(a,b,c,d,e){var f=a.toString();a=this.g[f];a||(a=this.g[f]=[],this.h++);var g=La(a,b,d,e);-1>>0);function Sa(a){if(\"function\"===typeof a)return a;a[$a]||(a[$a]=function(b){return a.handleEvent(b)});return a[$a]};function E(){z.call(this);this.i=new Ka(this);this.M=this;this.F=null}r(E,z);E.prototype[D]=!0;E.prototype.removeEventListener=function(a,b,c,d){Ya(this,a,b,c,d)};\nfunction F(a,b){var c,d=a.F;if(d)for(c=[];d;d=d.F)c.push(d);a=a.M;d=b.type||b;if(\"string\"===typeof b)b=new A(b,a);else if(b instanceof A)b.target=b.target||a;else{var e=b;b=new A(d,a);ua(b,e)}e=!0;if(c)for(var f=c.length-1;0<=f;f--){var g=b.g=c[f];e=ab(g,d,!0,b)&&e}g=b.g=a;e=ab(g,d,!0,b)&&e;e=ab(g,d,!1,b)&&e;if(c)for(f=0;f{a.g=null;a.i&&(a.i=!1,cb(a))},a.l);const b=a.h;a.h=null;a.m.apply(null,b)}class eb extends z{constructor(a,b){super();this.m=a;this.l=b;this.h=null;this.i=!1;this.g=null}j(a){this.h=arguments;this.g?this.i=!0:cb(this)}N(){super.N();this.g&&(k.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}};function G(a){z.call(this);this.h=a;this.g={}}r(G,z);var fb=[];function gb(a){qa(a.g,function(b,c){this.g.hasOwnProperty(c)&&Za(b)},a);a.g={}}G.prototype.N=function(){G.aa.N.call(this);gb(this)};G.prototype.handleEvent=function(){throw Error(\"EventHandler.handleEvent not implemented\");};var hb=k.JSON.stringify;var ib=k.JSON.parse;var jb=class{stringify(a){return k.JSON.stringify(a,void 0)}parse(a){return k.JSON.parse(a,void 0)}};function kb(){}kb.prototype.h=null;function lb(a){return a.h||(a.h=a.i())};function mb(){}var H={OPEN:\"a\",kb:\"b\",Ja:\"c\",wb:\"d\"};function nb(){A.call(this,\"d\")}r(nb,A);function ob(){A.call(this,\"c\")}r(ob,A);var I={},pb=null;function qb(){return pb=pb||new E}I.La=\"serverreachability\";function rb(a){A.call(this,I.La,a)}r(rb,A);function J(a){const b=qb();F(b,new rb(b,a))}I.STAT_EVENT=\"statevent\";function sb(a,b){A.call(this,I.STAT_EVENT,a);this.stat=b}r(sb,A);function K(a){const b=qb();F(b,new sb(b,a))}I.Ma=\"timingevent\";function tb(a,b){A.call(this,I.Ma,a);this.size=b}r(tb,A);\nfunction ub(a,b){if(\"function\"!==typeof a)throw Error(\"Fn must not be null and must be a function\");return k.setTimeout(function(){a()},b)};function vb(){this.g=!0}vb.prototype.xa=function(){this.g=!1};function wb(a,b,c,d,e,f){a.info(function(){if(a.g)if(f){var g=\"\";for(var m=f.split(\"&\"),q=0;qd.length)){var e=d[1];if(Array.isArray(e)&&!(1>e.length)){var f=e[0];if(\"noop\"!=f&&\"stop\"!=f&&\"close\"!=f)for(var g=1;gw)&&(3!=w||this.g&&(this.h.h||this.g.oa()||Nb(this.g)))){this.J||4!=w||7==b||(8==b||0>=O?J(3):J(2));Ob(this);var c=this.g.Z();this.X=c;b:if(Pb(this)){var d=Nb(this.g);a=\"\";var e=d.length,f=4==P(this.g);if(!this.h.i){if(\"undefined\"===typeof TextDecoder){Q(this);Qb(this);var g=\"\";break b}this.h.i=new k.TextDecoder}for(b=0;bb.length)return Gb;b=b.slice(d,d+c);a.C=d+c;return b}M.prototype.cancel=function(){this.J=!0;Q(this)};function Kb(a){a.S=Date.now()+a.I;Wb(a,a.I)}function Wb(a,b){if(null!=a.B)throw Error(\"WatchDog timer not null\");a.B=ub(p(a.ba,a),b)}function Ob(a){a.B&&(k.clearTimeout(a.B),a.B=null)}\nM.prototype.ba=function(){this.B=null;const a=Date.now();0<=a-this.S?(zb(this.i,this.A),2!=this.L&&(J(3),K(17)),Q(this),this.s=2,Qb(this)):Wb(this,this.S-a)};function Qb(a){0==a.j.G||a.J||Ub(a.j,a)}function Q(a){Ob(a);var b=a.M;b&&\"function\"==typeof b.ma&&b.ma();a.M=null;gb(a.U);a.g&&(b=a.g,a.g=null,b.abort(),b.ma())}\nfunction Rb(a,b){try{var c=a.j;if(0!=c.G&&(c.g==a||Xb(c.h,a)))if(!a.K&&Xb(c.h,a)&&3==c.G){try{var d=c.Da.g.parse(b)}catch(l){d=null}if(Array.isArray(d)&&3==d.length){var e=d;if(0==e[0])a:{if(!c.u){if(c.g)if(c.g.F+3E3e[2]&&c.F&&0==c.v&&!c.C&&(c.C=ub(p(c.Za,c),6E3));if(1>=ac(c.h)&&c.ca){try{c.ca()}catch(l){}c.ca=void 0}}else R(c,11)}else if((a.K||c.g==a)&&Yb(c),!t(b))for(e=c.Da.g.parse(b),b=0;b=a.j:!1}function ac(a){return a.h?1:a.g?a.g.size:0}function Xb(a,b){return a.h?a.h==b:a.g?a.g.has(b):!1}\nfunction bc(a,b){a.g?a.g.add(b):a.h=b}function dc(a,b){a.h&&a.h==b?a.h=null:a.g&&a.g.has(b)&&a.g.delete(b)}ic.prototype.cancel=function(){this.i=kc(this);if(this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const a of this.g.values())a.cancel();this.g.clear()}};function kc(a){if(null!=a.h)return a.i.concat(a.h.D);if(null!=a.g&&0!==a.g.size){let b=a.i;for(const c of a.g.values())b=b.concat(c.D);return b}return la(a.i)};function lc(a){if(a.V&&\"function\"==typeof a.V)return a.V();if(\"undefined\"!==typeof Map&&a instanceof Map||\"undefined\"!==typeof Set&&a instanceof Set)return Array.from(a.values());if(\"string\"===typeof a)return a.split(\"\");if(ha(a)){for(var b=[],c=a.length,d=0;db)throw Error(\"Bad port number \"+b);a.s=b}else a.s=null}function tc(a,b,c){b instanceof sc?(a.i=b,Ac(a.i,a.h)):(c||(b=vc(b,Bc)),a.i=new sc(b,a.h))}function S(a,b,c){a.i.set(b,c)}function Ib(a){S(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36));return a}\nfunction uc(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}function vc(a,b,c){return\"string\"===typeof a?(a=encodeURI(a).replace(b,Cc),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function Cc(a){a=a.charCodeAt(0);return\"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}var wc=/[#\\/\\?@]/g,yc=/[#\\?:]/g,xc=/[#\\?]/g,Bc=/[#\\?@]/g,zc=/#/g;function sc(a,b){this.h=this.g=null;this.i=a||null;this.j=!!b}\nfunction U(a){a.g||(a.g=new Map,a.h=0,a.i&&pc(a.i,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c)}))}h=sc.prototype;h.add=function(a,b){U(this);this.i=null;a=V(this,a);var c=this.g.get(a);c||this.g.set(a,c=[]);c.push(b);this.h+=1;return this};function Dc(a,b){U(a);b=V(a,b);a.g.has(b)&&(a.i=null,a.h-=a.g.get(b).length,a.g.delete(b))}function Ec(a,b){U(a);b=V(a,b);return a.g.has(b)}\nh.forEach=function(a,b){U(this);this.g.forEach(function(c,d){c.forEach(function(e){a.call(b,e,d,this)},this)},this)};h.na=function(){U(this);const a=Array.from(this.g.values()),b=Array.from(this.g.keys()),c=[];for(let d=0;d{d.abort();W(c,\"TestPingServer: timeout\",!1,b)},1E4);fetch(a,{signal:d.signal}).then(f=>{clearTimeout(e);f.ok?W(c,\"TestPingServer: ok\",!0,b):W(c,\"TestPingServer: server error\",!1,b)}).catch(()=>{clearTimeout(e);W(c,\"TestPingServer: error\",!1,b)})}function W(a,b,c,d,e){try{e&&(e.onload=null,e.onerror=null,e.onabort=null,e.ontimeout=null),d(c)}catch(f){}};function Hc(){this.g=new jb}function Ic(a,b,c){const d=c||\"\";try{nc(a,function(e,f){let g=e;n(e)&&(g=hb(e));b.push(d+f+\"=\"+encodeURIComponent(g))})}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}};function Jc(a){this.l=a.Ub||null;this.j=a.eb||!1}r(Jc,kb);Jc.prototype.g=function(){return new Kc(this.l,this.j)};Jc.prototype.i=function(a){return function(){return a}}({});function Kc(a,b){E.call(this);this.D=a;this.o=b;this.m=void 0;this.status=this.readyState=0;this.responseType=this.responseText=this.response=this.statusText=\"\";this.onreadystatechange=null;this.u=new Headers;this.h=null;this.B=\"GET\";this.A=\"\";this.g=!1;this.v=this.j=this.l=null}r(Kc,E);h=Kc.prototype;\nh.open=function(a,b){if(0!=this.readyState)throw this.abort(),Error(\"Error reopening a connection\");this.B=a;this.A=b;this.readyState=1;Lc(this)};h.send=function(a){if(1!=this.readyState)throw this.abort(),Error(\"need to call open() first. \");this.g=!0;const b={headers:this.u,method:this.B,credentials:this.m,cache:void 0};a&&(b.body=a);(this.D||k).fetch(new Request(this.A,b)).then(this.Sa.bind(this),this.ga.bind(this))};\nh.abort=function(){this.response=this.responseText=\"\";this.u=new Headers;this.status=0;this.j&&this.j.cancel(\"Request was aborted.\").catch(()=>{});1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Mc(this));this.readyState=0};\nh.Sa=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,Lc(this)),this.g&&(this.readyState=3,Lc(this),this.g)))if(\"arraybuffer\"===this.responseType)a.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(\"undefined\"!==typeof k.ReadableStream&&\"body\"in a){this.j=a.body.getReader();if(this.o){if(this.responseType)throw Error('responseType must be empty for \"streamBinaryChunks\" mode responses.');this.response=\n[]}else this.response=this.responseText=\"\",this.v=new TextDecoder;Nc(this)}else a.text().then(this.Ra.bind(this),this.ga.bind(this))};function Nc(a){a.j.read().then(a.Pa.bind(a)).catch(a.ga.bind(a))}h.Pa=function(a){if(this.g){if(this.o&&a.value)this.response.push(a.value);else if(!this.o){var b=a.value?a.value:new Uint8Array(0);if(b=this.v.decode(b,{stream:!a.done}))this.response=this.responseText+=b}a.done?Mc(this):Lc(this);3==this.readyState&&Nc(this)}};\nh.Ra=function(a){this.g&&(this.response=this.responseText=a,Mc(this))};h.Qa=function(a){this.g&&(this.response=a,Mc(this))};h.ga=function(){this.g&&Mc(this)};function Mc(a){a.readyState=4;a.l=null;a.j=null;a.v=null;Lc(a)}h.setRequestHeader=function(a,b){this.u.append(a,b)};h.getResponseHeader=function(a){return this.h?this.h.get(a.toLowerCase())||\"\":\"\"};\nh.getAllResponseHeaders=function(){if(!this.h)return\"\";const a=[],b=this.h.entries();for(var c=b.next();!c.done;)c=c.value,a.push(c[0]+\": \"+c[1]),c=b.next();return a.join(\"\\r\\n\")};function Lc(a){a.onreadystatechange&&a.onreadystatechange.call(a)}Object.defineProperty(Kc.prototype,\"withCredentials\",{get:function(){return\"include\"===this.m},set:function(a){this.m=a?\"include\":\"same-origin\"}});function Oc(a){let b=\"\";qa(a,function(c,d){b+=d;b+=\":\";b+=c;b+=\"\\r\\n\"});return b}function Pc(a,b,c){a:{for(d in c){var d=!1;break a}d=!0}d||(c=Oc(c),\"string\"===typeof a?(encodeURIComponent(String(b)),null!=c&&encodeURIComponent(String(c))):S(a,b,c))};function X(a){E.call(this);this.headers=new Map;this.o=a||null;this.h=!1;this.v=this.g=null;this.D=\"\";this.m=0;this.l=\"\";this.j=this.B=this.u=this.A=!1;this.I=null;this.H=\"\";this.J=!1}r(X,E);var Qc=/^https?$/i,Rc=[\"POST\",\"PUT\"];h=X.prototype;h.Ha=function(a){this.J=a};\nh.ea=function(a,b,c,d){if(this.g)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.D+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.D=a;this.l=\"\";this.m=0;this.A=!1;this.h=!0;this.g=this.o?this.o.g():Cb.g();this.v=this.o?lb(this.o):lb(Cb);this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(b,String(a),!0),this.B=!1}catch(f){Sc(this,f);return}a=c||\"\";c=new Map(this.headers);if(d)if(Object.getPrototypeOf(d)===Object.prototype)for(var e in d)c.set(e,d[e]);else if(\"function\"===\ntypeof d.keys&&\"function\"===typeof d.get)for(const f of d.keys())c.set(f,d.get(f));else throw Error(\"Unknown input type for opt_headers: \"+String(d));d=Array.from(c.keys()).find(f=>\"content-type\"==f.toLowerCase());e=k.FormData&&a instanceof k.FormData;!(0<=Array.prototype.indexOf.call(Rc,b,void 0))||d||e||c.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");for(const [f,g]of c)this.g.setRequestHeader(f,g);this.H&&(this.g.responseType=this.H);\"withCredentials\"in this.g&&this.g.withCredentials!==\nthis.J&&(this.g.withCredentials=this.J);try{Tc(this),this.u=!0,this.g.send(a),this.u=!1}catch(f){Sc(this,f)}};function Sc(a,b){a.h=!1;a.g&&(a.j=!0,a.g.abort(),a.j=!1);a.l=b;a.m=5;Uc(a);Vc(a)}function Uc(a){a.A||(a.A=!0,F(a,\"complete\"),F(a,\"error\"))}h.abort=function(a){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=a||7,F(this,\"complete\"),F(this,\"abort\"),Vc(this))};h.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Vc(this,!0));X.aa.N.call(this)};\nh.Ea=function(){this.s||(this.B||this.u||this.j?Wc(this):this.bb())};h.bb=function(){Wc(this)};\nfunction Wc(a){if(a.h&&\"undefined\"!=typeof fa&&(!a.v[1]||4!=P(a)||2!=a.Z()))if(a.u&&4==P(a))bb(a.Ea,0,a);else if(F(a,\"readystatechange\"),4==P(a)){a.h=!1;try{const g=a.Z();a:switch(g){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var b=!0;break a;default:b=!1}var c;if(!(c=b)){var d;if(d=0===g){var e=String(a.D).match(oc)[1]||null;!e&&k.self&&k.self.location&&(e=k.self.location.protocol.slice(0,-1));d=!Qc.test(e?e.toLowerCase():\"\")}c=d}if(c)F(a,\"complete\"),F(a,\"success\");else{a.m=\n6;try{var f=2{}:null;a.g=null;a.v=null;b||F(a,\"ready\");try{c.onreadystatechange=d}catch(e){}}}function Tc(a){a.I&&(k.clearTimeout(a.I),a.I=null)}h.isActive=function(){return!!this.g};function P(a){return a.g?a.g.readyState:0}h.Z=function(){try{return 2=a.h.j-(a.s?1:0))return!1;if(a.s)return a.i=b.D.concat(a.i),!0;if(1==a.G||2==a.G||a.B>=(a.Va?0:a.Wa))return!1;a.s=ub(p(a.Ga,a,b),cd(a,a.B));a.B++;return!0}\nh.Ga=function(a){if(this.s)if(this.s=null,1==this.G){if(!a){this.U=Math.floor(1E5*Math.random());a=this.U++;const e=new M(this,this.j,a);let f=this.o;this.S&&(f?(f=sa(f),ua(f,this.S)):f=this.S);null!==this.m||this.O||(e.H=f,f=null);if(this.P)a:{var b=0;for(var c=0;cl)f=Math.max(0,e[q].g-100),m=!1;else try{Ic(v,g,\"req\"+l+\"_\")}catch(w){d&&d(v)}}if(m){d=g.join(\"&\");break a}}}a=a.i.splice(0,c);b.D=a;return d}function ec(a){if(!a.g&&!a.u){a.Y=1;var b=a.Fa;x||Ea();y||(x(),y=!0);za.add(b,a);a.v=0}}\nfunction $b(a){if(a.g||a.u||3<=a.v)return!1;a.Y++;a.u=ub(p(a.Fa,a),cd(a,a.v));a.v++;return!0}h.Fa=function(){this.u=null;fd(this);if(this.ba&&!(this.M||null==this.g||0>=this.R)){var a=2*this.R;this.j.info(\"BP detection timer enabled: \"+a);this.A=ub(p(this.ab,this),a)}};h.ab=function(){this.A&&(this.A=null,this.j.info(\"BP detection timeout reached.\"),this.j.info(\"Buffering proxy detected and switch to long-polling!\"),this.F=!1,this.M=!0,K(10),Zb(this),fd(this))};\nfunction Tb(a){null!=a.A&&(k.clearTimeout(a.A),a.A=null)}function fd(a){a.g=new M(a,a.j,\"rpc\",a.Y);null===a.m&&(a.g.H=a.o);a.g.O=0;var b=N(a.qa);S(b,\"RID\",\"rpc\");S(b,\"SID\",a.K);S(b,\"AID\",a.T);S(b,\"CI\",a.F?\"0\":\"1\");!a.F&&a.ja&&S(b,\"TO\",a.ja);S(b,\"TYPE\",\"xmlhttp\");$c(a,b);a.m&&a.o&&Pc(b,a.m,a.o);a.L&&(a.g.I=a.L);var c=a.g;a=a.ia;c.L=1;c.v=Ib(N(b));c.m=null;c.P=!0;Jb(c,a)}h.Za=function(){null!=this.C&&(this.C=null,Zb(this),$b(this),K(19))};function Yb(a){null!=a.C&&(k.clearTimeout(a.C),a.C=null)}\nfunction Ub(a,b){var c=null;if(a.g==b){Yb(a);Tb(a);a.g=null;var d=2}else if(Xb(a.h,b))c=b.D,dc(a.h,b),d=1;else return;if(0!=a.G)if(b.o)if(1==d){c=b.m?b.m.length:0;b=Date.now()-b.F;var e=a.B;d=qb();F(d,new tb(d,c,b,e));fc(a)}else ec(a);else if(e=b.s,3==e||0==e&&0\n *
  • `debug` for the most verbose logging level, primarily for\n * debugging.
  • \n *
  • `error` to log errors only.
  • \n *
  • `silent` to turn off logging.
  • \n * \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(\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 cannot 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 {\n (value: R | Promise): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport class Deferred {\n promise: Promise;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver, 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(\n values: T[],\n fn: (value: T) => Promise\n): Promise {\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;\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;\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 = (credential: T) => Promise;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /**\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\n ): void;\n\n /** Requests a token for the current user. */\n getToken(): Promise;\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 {\n getToken(): Promise {\n return Promise.resolve(null);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\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\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 | null = null;\n\n getToken(): Promise {\n return Promise.resolve(this.token);\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\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 {\n private auth: FirebaseAuthInternal | null = null;\n\n constructor(authProvider: Provider) {\n authProvider.onInit(auth => {\n this.auth = auth;\n });\n }\n\n getToken(): Promise {\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\n ): void {}\n\n shutdown(): void {}\n}\n\nexport class FirebaseAuthCredentialsProvider\n implements CredentialsProvider\n{\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: (() => void) | undefined;\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) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 'Token listener already added'\n );\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 = 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();\n\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n nextToken.resolve();\n nextToken = new Deferred();\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 if (this.tokenListener) {\n this.auth.addAuthTokenListener(this.tokenListener);\n awaitNextToken();\n }\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();\n }\n }\n }, 0);\n\n awaitNextToken();\n }\n\n getToken(): Promise {\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 && this.tokenListener) {\n this.auth.removeAuthTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\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 {\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\n{\n constructor(\n private sessionIndex: string,\n private iamToken: string | null,\n private authTokenFactory: AuthTokenFactory | null\n ) {}\n\n getToken(): Promise {\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\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\n{\n /**\n * The AppCheck token listener registered with FirebaseApp, retained here so\n * we can unregister it.\n */\n private tokenListener: AppCheckTokenListener | undefined;\n private forceRefresh = false;\n private appCheck: FirebaseAppCheckInternal | null = null;\n private latestAppCheckToken: string | null = null;\n\n constructor(\n private appCheckProvider: Provider\n ) {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 'Token listener already added'\n );\n\n const onTokenChanged: (\n tokenResult: AppCheckTokenResult\n ) => Promise = 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 if (this.tokenListener) {\n this.appCheck.addTokenListener(this.tokenListener);\n }\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 {\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 && this.tokenListener) {\n this.appCheck.removeTokenListener(this.tokenListener);\n }\n this.tokenListener = undefined;\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */\nexport class EmptyAppCheckTokenProvider implements CredentialsProvider {\n getToken(): Promise {\n return Promise.resolve(new AppCheckToken(''));\n }\n\n invalidateToken(): void {}\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {}\n\n shutdown(): void {}\n}\n\n/** AppCheck token provider for the Lite SDK. */\nexport class LiteAppCheckTokenProvider implements CredentialsProvider {\n private appCheck: FirebaseAppCheckInternal | null = null;\n\n constructor(\n private appCheckProvider: Provider\n ) {\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\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\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 {\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 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 { randomBytes } from '../platform/random_bytes';\n\nimport { debugAssert } from './assert';\n\nexport type EventHandler = (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(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 {\n isEqual(other: T): boolean;\n}\n\nexport interface Iterable {\n forEach: (cb: (v: V) => void) => void;\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals(\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 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 . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexicographical ordering that matches\n // the expected ordering. The 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 lexicographical 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> {\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>(\n p1: BasePath,\n p2: BasePath\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 {\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 trailing 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 {\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;\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 {\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 =\n | ((result: T) => R | PersistencePromise)\n | null;\nexport type RejectedHandler =\n | ((reason: Error) => R | PersistencePromise)\n | null;\nexport type Resolver = (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 {\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 = null;\n private catchCallback: RejectedHandler = 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, 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(\n fn: (error: Error) => R | PersistencePromise\n ): PersistencePromise {\n return this.next(undefined, fn);\n }\n\n next(\n nextFn?: FulfilledHandler,\n catchFn?: RejectedHandler\n ): PersistencePromise {\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((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 {\n return new Promise((resolve, reject) => {\n this.next(resolve, reject);\n });\n }\n\n private wrapUserFunction(\n fn: () => R | PersistencePromise\n ): PersistencePromise {\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(e as Error);\n }\n }\n\n private wrapSuccess(\n nextFn: FulfilledHandler | undefined,\n value: T\n ): PersistencePromise {\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(value as unknown as R);\n }\n }\n\n private wrapFailure(\n catchFn: RejectedHandler | undefined,\n error: Error\n ): PersistencePromise {\n if (catchFn) {\n return this.wrapUserFunction(() => catchFn(error));\n } else {\n return PersistencePromise.reject(error);\n }\n }\n\n static resolve(): PersistencePromise;\n static resolve(result: R): PersistencePromise;\n static resolve(result?: R): PersistencePromise {\n return new PersistencePromise((resolve, reject) => {\n resolve(result);\n });\n }\n\n static reject(error: Error): PersistencePromise {\n return new PersistencePromise((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) => void) => void }\n ): PersistencePromise {\n return new PersistencePromise((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>\n ): PersistencePromise {\n let p: PersistencePromise =\n PersistencePromise.resolve(false);\n for (const predicate of predicates) {\n p = p.next(isTrue => {\n if (isTrue) {\n return PersistencePromise.resolve(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(\n collection: { forEach: (cb: (r: R, s: S) => void) => void },\n f:\n | ((r: R, s: S) => PersistencePromise)\n | ((r: R) => PersistencePromise)\n ): PersistencePromise;\n static forEach(\n collection: { forEach: (cb: (r: R) => void) => void },\n f: (r: R) => PersistencePromise\n ): PersistencePromise;\n static forEach(\n collection: { forEach: (cb: (r: R, s?: S) => void) => void },\n f: (r: R, s?: S) => PersistencePromise\n ): PersistencePromise {\n const promises: Array> = [];\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(\n array: T[],\n f: (t: T) => PersistencePromise\n ): PersistencePromise {\n return new PersistencePromise((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\n ): PersistencePromise {\n return new PersistencePromise((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;\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();\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 {\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 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(\n storeName: string\n ): SimpleDbStore {\n const store = this.transaction.objectStore(storeName);\n debugAssert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(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 {\n logDebug(LOG_TAG, 'Removing database:', name);\n return wrapRequest(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 users running version < 4.5.\n const androidVersion = 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(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore {\n return txn.store(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 /*\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 {\n if (!this.db) {\n logDebug(LOG_TAG, 'Opening database:', this.name);\n this.db = await new Promise((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(\n action: string,\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise\n ): Promise {\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(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/** Parse User Agent to determine Android version. Returns -1 if not found. */\nexport function 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 * 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 {\n return wrapRequest(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise;\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 /** IndexedDB 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;\n put(key: KeyType, value: ValueType): PersistencePromise;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise {\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, '', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest(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 {\n logDebug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest(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 {\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(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 {\n logDebug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest(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 {\n logDebug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest(request);\n }\n\n /** Loads all elements from the object store. */\n loadAll(): PersistencePromise;\n /** Loads all elements for the index range from the object store. */\n loadAll(range: IDBKeyRange): PersistencePromise;\n /** Loads all elements ordered by the given index. */\n loadAll(index: string): PersistencePromise;\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;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\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 {\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;\n deleteAll(range: IDBKeyRange): PersistencePromise;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise {\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\n ): PersistencePromise;\n iterate(\n options: IterateOptions,\n callback: IterateCallback\n ): PersistencePromise;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback,\n callback?: IterateCallback\n ): PersistencePromise {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback;\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\n ): PersistencePromise {\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\n ): PersistencePromise {\n const results: Array> = [];\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 = 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(request: IDBRequest): PersistencePromise {\n return new PersistencePromise((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 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 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/**\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/** Name of the IndexedDb object store. */\nexport const DbGlobalsStore = 'globals';\n\nexport const DbGlobalsKeyPath = 'name';\n\n/** Names of global values */\nexport type DbGlobalsKey = 'sessionToken';\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];\nexport const V16_STORES = V15_STORES;\nexport const V17_STORES = [...V15_STORES, DbGlobalsStore];\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 === 17) {\n return V17_STORES;\n } else if (schemaVersion === 16) {\n return V16_STORES;\n } else 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 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 {\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(\n obj: Dict | 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(\n obj: Dict,\n fn: (element: V, key: string, obj: Dict) => 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(obj: Dict): 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 = (key1: K, key2: K) => number;\n\nexport interface Entry {\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 {\n // visible for testing\n root: LLRBNode | LLRBEmptyNode;\n\n constructor(\n public comparator: Comparator,\n root?: LLRBNode | LLRBEmptyNode\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 {\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 // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // 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(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).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(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator {\n private isReverse: boolean;\n private nodeStack: Array | LLRBEmptyNode>;\n\n constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\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 {\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 | 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 {\n readonly color: boolean;\n readonly left: LLRBNode | LLRBEmptyNode;\n readonly right: LLRBNode | LLRBEmptyNode;\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 = 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 | LLRBEmptyNode,\n right?: LLRBNode | LLRBEmptyNode\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 | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n 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(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode).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(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min();\n }\n }\n\n // 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): LLRBNode {\n let n: LLRBNode = 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 | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode = 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).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\n ): LLRBNode | LLRBEmptyNode {\n let smallest: LLRBNode;\n let n: LLRBNode = 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).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp();\n }\n\n isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode {\n let n: LLRBNode = 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 {\n let n = this.colorFlip();\n if (n.right.left.isRed()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode {\n let n = this.colorFlip();\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n return n;\n }\n\n private rotateLeft(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n // 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).check();\n if (blackDepth !== (this.right as LLRBNode).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 {\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 | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\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): LLRBNode {\n return new LLRBNode(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator): LLRBEmptyNode {\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();\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 {\n private data: SortedMap;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap(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] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator;\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 {\n return new SortedSetIterator(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator {\n return new SortedSetIterator(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet {\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): SortedSet {\n let result: SortedSet = 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): 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): SortedSet {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator {\n constructor(private iter: SortedMapIterator) {}\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(\n before: SortedSet,\n after: SortedSet,\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(it: SortedSetIterator): 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.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 {\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 as ProtoValue,\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\nexport const TYPE_KEY = '__type__';\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 VECTOR_VALUE_SENTINEL = '__vector__';\nexport const VECTOR_MAP_VECTORS_KEY = 'value';\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 } else if (isVectorValue(value)) {\n return TypeOrder.VectorValue;\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.VectorValue:\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.VectorValue:\n return compareVectors(left.mapValue!, right.mapValue!);\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 compareVectors(left: MapValue, right: MapValue): number {\n const leftMap = left.fields || {};\n const rightMap = right.fields || {};\n\n // The vector is a map, but only vector value is compared.\n const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue;\n\n const lengthCompare = primitiveComparator(\n leftArrayValue?.values?.length || 0,\n rightArrayValue?.values?.length || 0\n );\n if (lengthCompare !== 0) {\n return lengthCompare;\n }\n\n return compareArrays(leftArrayValue!, rightArrayValue!);\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.VectorValue:\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/** Returns true if `value` is a VetorValue. */\nexport function isVectorValue(value: ProtoValue | null): boolean {\n const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue;\n return type === VECTOR_VALUE_SENTINEL;\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\nexport const MIN_VECTOR_VALUE = {\n mapValue: {\n fields: {\n [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {}\n }\n }\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 if (isVectorValue(value)) {\n return MIN_VECTOR_VALUE;\n }\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 MIN_VECTOR_VALUE;\n } else if ('mapValue' in value) {\n if (isVectorValue(value)) {\n return { mapValue: {} };\n }\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 {\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): 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 {\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,\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 synced 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();\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.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 {\n let result = new SortedSet(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();\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` sorts the key field before other fields. However, we want the key\n // field to be sorted last.\n const inequalityFields: SortedSet =\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];\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 {\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>;\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;\nconst EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap(\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;\n}\n\nexport type DocumentMap = SortedMap;\nconst EMPTY_DOCUMENT_MAP = new SortedMap(\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;\nexport function newOverlayedDocumentMap(): OverlayedDocumentMap {\n return newDocumentKeyMap();\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;\nexport function newOverlayMap(): OverlayMap {\n return newDocumentKeyMap();\n}\n\nexport type MutationMap = DocumentKeyMap;\nexport function newMutationMap(): MutationMap {\n return newDocumentKeyMap();\n}\n\nexport type DocumentKeyMap = ObjectMap;\nexport function newDocumentKeyMap(): DocumentKeyMap {\n return new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n}\n\nexport type DocumentVersionMap = SortedMap;\nconst EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(\n DocumentKey.comparator\n);\nexport function documentVersionMap(): DocumentVersionMap {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nexport type DocumentKeySet = SortedSet;\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;\nconst EMPTY_TARGET_ID_SET = new SortedSet(primitiveComparator);\nexport function targetIdSet(): SortedSet {\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\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.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 {\n const result = new Map();\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\n): Map {\n const transformResults = new Map();\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 {\n const transformResults = new Map();\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=>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 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 dependent 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 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 global, singleton instance of TestingHooksSpi.\n *\n * This variable will be `null` in all cases _except_ when running from\n * integration tests that have registered callbacks to be notified of events\n * that happen during the test execution.\n */\nexport let testingHooksSpi: TestingHooksSpi | null = null;\n\n/**\n * Sets the value of the `testingHooksSpi` object.\n * @param instance the instance to set.\n */\nexport function setTestingHooksSpi(instance: TestingHooksSpi): void {\n if (testingHooksSpi) {\n throw new Error('a TestingHooksSpi instance is already set');\n }\n testingHooksSpi = instance;\n}\n\n/**\n * The \"service provider interface\" for the testing hooks.\n *\n * The implementation of this object will handle the callbacks made by the SDK\n * to be handled by the integration tests.\n *\n * This \"SPI\" is separated from the implementation to avoid import cycles and\n * to enable production builds to fully tree-shake away the testing hooks logic.\n */\nexport interface TestingHooksSpi {\n /**\n * Invokes all callbacks registered with\n * `TestingHooks.onExistenceFilterMismatch()` with the given info.\n */\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void;\n}\n\n/**\n * Information about an existence filter mismatch.\n * @internal\n */\nexport interface ExistenceFilterMismatchInfo {\n /** The number of documents that matched the query in the local cache. */\n localCacheCount: number;\n\n /**\n * The number of documents that matched the query on the server, as specified\n * in the ExistenceFilter message's `count` field.\n */\n existenceFilterCount: number;\n\n /**\n * The projectId used when checking documents for membership in the bloom\n * filter.\n */\n projectId: string;\n\n /**\n * The databaseId used when checking documents for membership in the bloom\n * filter.\n */\n databaseId: string;\n\n /**\n * Information about the bloom filter provided by Watch in the ExistenceFilter\n * message's `unchangedNames` field. If this property is omitted or undefined\n * then that means that Watch did _not_ provide a bloom filter.\n */\n bloomFilter?: {\n /**\n * Whether a full requery was averted by using the bloom filter. If false,\n * then something happened, such as a false positive, to prevent using the\n * bloom filter to avoid a full requery.\n */\n applied: boolean;\n\n /** The number of hash functions used in the bloom filter. */\n hashCount: number;\n\n /** The number of bytes in the bloom filter's bitmask. */\n bitmapLength: number;\n\n /** The number of bits of padding in the last byte of the bloom filter. */\n padding: number;\n\n /**\n * Tests the given string for membership in the bloom filter created from\n * the existence filter; will be undefined if creating the bloom filter\n * failed.\n */\n mightContain?: (value: string) => boolean;\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 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 */\n\nimport { Md5, Integer } from '@firebase/webchannel-wrapper/bloom-blob';\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// 2’s 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,\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,\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();\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(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 =\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();\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(\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();\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(\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 {\n let targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(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> {\n return new SortedMap>(\n DocumentKey.comparator\n );\n}\n\nfunction snapshotChangesMap(): SortedMap {\n return new SortedMap(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: } 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 ||\n // Check if the value is an instance of both Buffer and Uint8Array,\n // despite the fact that Buffer extends Uint8Array. In some\n // environments, such as jsdom, the prototype chain of Buffer\n // does not indicate that it extends Uint8Array.\n value instanceof Buffer ||\n value instanceof Uint8Array,\n 'value must be undefined, Buffer, 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 skipAliasing?: boolean\n): {\n request: ProtoRunAggregationQueryRequest;\n aliasMap: Record;\n parent: ResourcePath;\n} {\n const { queryTarget, parent } = toQueryTarget(serializer, target);\n const aliasMap: Record = {};\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 = skipAliasing\n ? aggregate.alias\n : `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 | 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 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 {\n normalizeByteString,\n normalizeNumber,\n normalizeTimestamp\n} from '../model/normalize';\nimport {\n isVectorValue,\n VECTOR_MAP_VECTORS_KEY,\n isMaxValue\n} 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_VECTOR = 53;\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 let timestamp = indexValue.timestampValue!;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_TIMESTAMP);\n if (typeof timestamp === 'string') {\n timestamp = normalizeTimestamp(timestamp);\n }\n encoder.writeString(`${timestamp.seconds || ''}`);\n encoder.writeNumber(timestamp.nanos || 0);\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 if (isVectorValue(indexValue)) {\n this.writeIndexVector(indexValue.mapValue!, encoder);\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 writeIndexVector(\n mapIndexValue: MapValue,\n encoder: DirectionalIndexByteEncoder\n ): void {\n const map = mapIndexValue.fields || {};\n this.writeValueTypeLabel(encoder, INDEX_TYPE_VECTOR);\n\n // Vectors sort first by length\n const key = VECTOR_MAP_VECTORS_KEY;\n const length = map[key].arrayValue?.values?.length || 0;\n this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER);\n encoder.writeNumber(normalizeNumber(length));\n\n // Vectors then sort by position value\n this.writeIndexString(key, encoder);\n this.writeIndexValueAux(map[key], encoder);\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 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 {\n this.collectionParentIndex.add(collectionPath);\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise {\n return PersistencePromise.resolve(\n this.collectionParentIndex.getEntries(collectionId)\n );\n }\n\n addFieldIndex(\n transaction: PersistenceTransaction,\n index: FieldIndex\n ): PersistencePromise {\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 {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve();\n }\n\n deleteAllFieldIndexes(\n transaction: PersistenceTransaction\n ): PersistencePromise {\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 {\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 {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n\n getIndexType(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(IndexType.NONE);\n }\n\n getFieldIndexes(\n transaction: PersistenceTransaction,\n collectionGroup?: string\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve([]);\n }\n\n getNextCollectionGroupToUpdate(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n // Field indices are not supported with memory persistence.\n return PersistencePromise.resolve(null);\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n getMinOffsetFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string\n ): PersistencePromise {\n return PersistencePromise.resolve(IndexOffset.min());\n }\n\n updateCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset\n ): PersistencePromise {\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 {\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;\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.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.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(\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 {\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 {\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 {\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 {\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 {\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 {\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 {\n const indexEntries = indexEntriesStore(transaction);\n\n let canServeTarget = true;\n const indexes = new Map();\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 {\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 {\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 {\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 {\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 {\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 {\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();\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 {\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 {\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> {\n const indexEntries = indexEntriesStore(transaction);\n let results = new SortedSet(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 {\n let results = new SortedSet(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,\n newEntries: SortedSet\n ): PersistencePromise {\n logDebug(LOG_TAG, \"Updating index entries for document '%s'\", document.key);\n\n const promises: Array> = [];\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 {\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 {\n return this.getFieldIndexes(transaction, collectionGroup).next(\n getMinOffsetFromFieldIndexes\n );\n }\n\n getMinOffset(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\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 {\n return getStore(\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 {\n return getStore(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 {\n return getStore(\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 {\n return getStore(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;\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;\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;\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise;\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;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\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;\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;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise;\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;\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;\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;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise;\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 { 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 = 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;\n\n protected abstract getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise;\n\n protected abstract applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise;\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 {\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 {\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 {\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 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 {\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 {\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 {\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 {\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 {\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 {\n let recalculateDocuments = mutableDocumentMap();\n const mutatedFields = newDocumentKeyMap();\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> {\n const masks = newDocumentKeyMap();\n // A reverse lookup map from batch id to the documents within that batch.\n let documentsByBatchId = new SortedMap(\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> = [];\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> {\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 {\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 *

    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 {\n return this.remoteDocumentCache\n .getAllFromCollectionGroup(transaction, collectionGroup, offset, count)\n .next((originalDocs: MutableDocumentMap) => {\n const overlaysPromise: PersistencePromise =\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 {\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 {\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 {\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();\n private namedQueries = new Map();\n\n constructor(private serializer: LocalSerializer) {}\n\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return PersistencePromise.resolve(this.bundles.get(bundleId));\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n this.bundles.set(bundleMetadata.id!, fromBundleMetadata(bundleMetadata));\n return PersistencePromise.resolve();\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return PersistencePromise.resolve(this.namedQueries.get(queryName));\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\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(\n DocumentKey.comparator\n );\n private overlayByBatchId = new Map();\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return PersistencePromise.resolve(this.overlays.get(key));\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\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 {\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 {\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 {\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 {\n let batchIdToOverlays = new SortedMap(\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 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ByteString } from '../util/byte_string';\n\nimport { GlobalsCache } from './globals_cache';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\nexport class MemoryGlobalsCache implements GlobalsCache {\n private sessionToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n\n getSessionToken(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.sessionToken);\n }\n\n setSessionToken(\n transaction: PersistenceTransaction,\n sessionToken: ByteString\n ): PersistencePromise {\n this.sessionToken = sessionToken;\n return PersistencePromise.resolve();\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 {\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 {\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 {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\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 {\n return PersistencePromise.resolve(\n this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1\n );\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\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\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(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 {\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(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): 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 {\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 {\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 {\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 removed 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 efficient.\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;\nfunction documentEntryMap(): DocumentEntryMap {\n return new SortedMap(\n DocumentKey.comparator\n );\n}\n\nexport interface MemoryRemoteDocumentCache extends RemoteDocumentCache {\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise\n ): PersistencePromise;\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 {\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 {\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 {\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 {\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 limit: number\n ): PersistencePromise {\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\n ): PersistencePromise {\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 {\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 {\n const promises: Array> = [];\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 {\n return this.documentCache.getEntry(transaction, documentKey);\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\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(\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 {\n this.targets.forEach((_, targetData) => f(targetData));\n return PersistencePromise.resolve();\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return PersistencePromise.resolve(this.highestSequenceNumber);\n }\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\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 {\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 {\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 {\n debugAssert(\n this.targets.has(targetData.target),\n 'Updating a nonexistent target'\n );\n this.saveTargetData(targetData);\n return PersistencePromise.resolve();\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n debugAssert(this.targetCount > 0, 'Removing a target from an empty cache');\n debugAssert(\n this.targets.has(targetData.target),\n 'Removing a nonexistent 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 {\n let count = 0;\n const removals: Array> = [];\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 {\n return PersistencePromise.resolve(this.targetCount);\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\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 {\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 {\n this.references.removeReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array> = [];\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 {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\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 { GlobalsCache } from './globals_cache';\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 { MemoryGlobalsCache } from './memory_globals_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 readonly globalsCache: MemoryGlobalsCache;\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.globalsCache = new MemoryGlobalsCache();\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 {\n return Promise.resolve();\n }\n\n shutdown(): Promise {\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 getGlobalsCache(): GlobalsCache {\n return this.globalsCache;\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(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\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 {\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;\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 | 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 {\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 {\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 {\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 {\n this.orphanedDocuments.add(key.toString());\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\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();\n }\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise {\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 {\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 {\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 {\n return PersistencePromise.resolve();\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.persistence.getTargetCache().forEachTarget(txn, f);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\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 {\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 {\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 {\n return this.persistence\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\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 {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\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 {\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 {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\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 {\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 {\n return this.persistence.getRemoteDocumentCache().getSize(txn);\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 '../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 { getAndroidVersion } 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 (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 {\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 {\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 {\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(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;\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 {\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(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(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(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(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 {\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(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,\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 {\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,\n query: Query,\n offset: IndexOffset\n ): PersistencePromise {\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(primitiveComparator);\n\n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n targetIdByTarget = new ObjectMap(\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();\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 {\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 {\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 {\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 {\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 {\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 {\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 {\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 {\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>;\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 {\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 {\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 {\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 {\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 {\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 {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const targetId = localStoreImpl.targetIdByTarget.get(target);\n if (targetId !== undefined) {\n return PersistencePromise.resolve(\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 {\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 {\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 {\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 {\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;\n } else {\n return PersistencePromise.resolve(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 {\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 {\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 {\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\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 {\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 {\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 {\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 {\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 {\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 {\n const localStoreImpl = debugCast(localStore, LocalStoreImpl);\n const indexManager = localStoreImpl.indexManager;\n const promises: Array> = [];\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 {\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 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(\n targetId: TargetId,\n addToActiveTargetIds?: boolean\n ): 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;\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;\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): 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 the watch.\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(\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 {\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(\n targetId: TargetId,\n addToActiveTargetIds: boolean = true\n ): 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 // If the query is listening to cache only, the target ID should not be registered with the\n // local Firestore client as an active watch target.\n if (addToActiveTargetIds) {\n this.localClientState.addQueryTarget(targetId);\n }\n\n this.persistClientState();\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): 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): 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 {\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 {\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 {\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\n ): SortedSet {\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(\n targetId: TargetId,\n addToActiveTargetIds: boolean = true\n ): QueryTargetState {\n if (addToActiveTargetIds) {\n this.localState.addQueryTarget(targetId);\n }\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 {\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): 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(\n rpcName: string,\n path: ResourcePath,\n req: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\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(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(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null,\n expectedResponseCount?: number\n ): Promise {\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(\n rpcName,\n path,\n request,\n authToken,\n appCheckToken\n );\n }\n\n abstract openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream;\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(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise;\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 implements Stream {\n private wrappedOnConnected: (() => void) | undefined;\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 onConnected(callback: () => void): void {\n debugAssert(\n !this.wrappedOnConnected,\n 'Called onConnected on stream twice!'\n );\n this.wrappedOnConnected = callback;\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 callOnConnected(): void {\n debugAssert(\n this.wrappedOnConnected !== undefined,\n 'Cannot call onConnected because no callback was set'\n );\n this.wrappedOnConnected();\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/webchannel-blob';\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(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req\n ): Promise {\n const streamId = generateUniqueDebugId();\n return new Promise((resolve: Resolver, 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(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\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({\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 = (\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 streamBridge.callOnConnected();\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(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(\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(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 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 | 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 {\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 receiving an acknowledgement from the server, confirming that\n * we are able to connect to it.\n */\n onConnected: () => Promise;\n /**\n * Called after the stream was established and can accept outgoing\n * messages\n */\n onOpen: () => Promise;\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;\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 | null = null;\n private healthCheck: DelayedOperation | null = null;\n private stream: Stream | 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,\n private appCheckCredentialsProvider: CredentialsProvider,\n protected listener: ListenerType\n ) {\n this.backoff = new ExponentialBackoff(queue, connectionTimerId);\n }\n\n /**\n * Count of response messages received.\n */\n protected responseCount: number = 0;\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 this.responseCount = 0;\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 {\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 {\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 {\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;\n\n /**\n * Called when the stream receives first message.\n * The function will be called on the right queue and must return a Promise.\n * @param message - The message received from the stream.\n */\n protected abstract onFirst(message: ReceiveType): Promise;\n\n /**\n * Called on subsequent messages after the stream has received first message.\n * The function will be called on the right queue and must return a Promise.\n * @param message - The message received from the stream.\n */\n protected abstract onNext(message: ReceiveType): Promise;\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.onConnected(() => {\n dispatchIfNotClosed(() => this.listener!.onConnected());\n });\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 if (++this.responseCount === 1) {\n return this.onFirst(msg);\n } else {\n return this.onNext(msg);\n }\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 {\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 {\n return (fn: () => Promise): 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;\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,\n appCheckCredentials: CredentialsProvider,\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 {\n return this.connection.openStream(\n 'Listen',\n authToken,\n appCheckToken\n );\n }\n\n protected onFirst(watchChangeProto: ProtoListenResponse): Promise {\n return this.onNext(watchChangeProto);\n }\n\n protected onNext(watchChangeProto: ProtoListenResponse): Promise {\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;\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;\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 constructor(\n queue: AsyncQueue,\n connection: Connection,\n authCredentials: CredentialsProvider,\n appCheckCredentials: CredentialsProvider,\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.responseCount > 0;\n }\n\n // Override of PersistentStream.start\n start(): void {\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 {\n return this.connection.openStream(\n 'Write',\n authToken,\n appCheckToken\n );\n }\n\n protected onFirst(responseProto: ProtoWriteResponse): Promise {\n // Always capture the last stream token.\n hardAssert(\n !!responseProto.streamToken,\n 'Got a write handshake response without a stream token'\n );\n this.lastStreamToken = responseProto.streamToken;\n\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 return this.listener!.onHandshakeComplete();\n }\n\n protected onNext(responseProto: ProtoWriteResponse): Promise {\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 // 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 * 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,\n readonly appCheckCredentials: CredentialsProvider,\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(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req\n ): Promise {\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(\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(\n rpcName: string,\n databaseId: DatabaseId,\n resourcePath: ResourcePath,\n request: Req,\n expectedResponseCount?: number\n ): Promise {\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(\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,\n appCheckCredentials: CredentialsProvider,\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 {\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 {\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();\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 {\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> {\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\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 | 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();\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();\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> = [];\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 {\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 {\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 {\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 {\n for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) {\n await networkStatusHandler(/* enabled= */ false);\n }\n}\n\nexport async function remoteStoreShutdown(\n remoteStore: RemoteStore\n): Promise {\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 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 onWatchStreamConnected(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n // Mark the client as online since we got a \"connected\" notification.\n remoteStoreImpl.onlineStateTracker.set(OnlineState.Online);\n}\n\nasync function onWatchStreamOpen(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\n remoteStoreImpl.listenTargets.forEach((targetData, targetId) => {\n sendWatchRequest(remoteStoreImpl, targetData);\n });\n}\n\nasync function onWatchStreamClose(\n remoteStoreImpl: RemoteStoreImpl,\n error?: FirestoreError\n): Promise {\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 {\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\n): Promise {\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\n): Promise {\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 {\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 {\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 {\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 {\n ensureWriteStream(remoteStoreImpl).writeHandshake();\n}\n\nasync function onWriteHandshakeComplete(\n remoteStoreImpl: RemoteStoreImpl\n): Promise {\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 {\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 {\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 {\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 {\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 {\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 {\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 onConnected: onWatchStreamConnected.bind(null, remoteStoreImpl),\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 onConnected: () => Promise.resolve(),\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 implements PromiseLike {\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();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise,\n private readonly removalCallback: (op: DelayedOperation) => 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 {\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(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise,\n removalCallback: (op: DelayedOperation) => void\n ): DelayedOperation {\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(op: () => Promise): 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(\n op: () => Promise\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 with `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(op: () => Promise): Promise;\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;\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(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation;\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;\n private sortedSet: SortedMap;\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(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,\n sortedSet: SortedMap\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(\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 { Code, 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 // Helper methods that checks if the query has listeners that listening to remote store\n hasRemoteListeners(): boolean {\n return this.listeners.some(listener => listener.listensToRemoteStore());\n }\n}\n\n/**\n * Interface for handling events from the EventManager.\n */\nexport interface Observer {\n next: EventHandler;\n error: EventHandler;\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?: (\n query: Query,\n enableRemoteListen: boolean\n ) => Promise;\n onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise;\n onFirstRemoteStoreListen?: (query: Query) => Promise;\n onLastRemoteStoreUnlisten?: (query: Query) => Promise;\n terminate(): void;\n}\n\nexport function newEventManager(): EventManager {\n return new EventManagerImpl();\n}\n\nexport class EventManagerImpl implements EventManager {\n queries: ObjectMap = newQueriesObjectMap();\n\n onlineState: OnlineState = OnlineState.Unknown;\n\n snapshotsInSyncListeners: Set> = new Set();\n\n /** Callback invoked when a Query is first listen to. */\n onListen?: (\n query: Query,\n enableRemoteListen: boolean\n ) => Promise;\n /** Callback invoked once all listeners to a Query are removed. */\n onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise;\n\n /**\n * Callback invoked when a Query starts listening to the remote store, while\n * already listening to the cache.\n */\n onFirstRemoteStoreListen?: (query: Query) => Promise;\n /**\n * Callback invoked when a Query stops listening to the remote store, while\n * still listening to the cache.\n */\n onLastRemoteStoreUnlisten?: (query: Query) => Promise;\n\n terminate(): void {\n errorAllTargets(\n this,\n new FirestoreError(Code.ABORTED, 'Firestore shutting down')\n );\n }\n}\n\nfunction newQueriesObjectMap(): ObjectMap {\n return new ObjectMap(\n q => canonifyQuery(q),\n queryEquals\n );\n}\n\nfunction validateEventManager(eventManagerImpl: EventManagerImpl): void {\n debugAssert(!!eventManagerImpl.onListen, 'onListen not set');\n debugAssert(\n !!eventManagerImpl.onFirstRemoteStoreListen,\n 'onFirstRemoteStoreListen not set'\n );\n debugAssert(!!eventManagerImpl.onUnlisten, 'onUnlisten not set');\n debugAssert(\n !!eventManagerImpl.onLastRemoteStoreUnlisten,\n 'onLastRemoteStoreUnlisten not set'\n );\n}\n\nconst enum ListenerSetupAction {\n InitializeLocalListenAndRequireWatchConnection,\n InitializeLocalListenOnly,\n RequireWatchConnectionOnly,\n NoActionRequired\n}\n\nconst enum ListenerRemovalAction {\n TerminateLocalListenAndRequireWatchDisconnection,\n TerminateLocalListenOnly,\n RequireWatchDisconnectionOnly,\n NoActionRequired\n}\n\nexport async function eventManagerListen(\n eventManager: EventManager,\n listener: QueryListener\n): Promise {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n validateEventManager(eventManagerImpl);\n\n let listenerAction = ListenerSetupAction.NoActionRequired;\n\n const query = listener.query;\n\n let queryInfo = eventManagerImpl.queries.get(query);\n if (!queryInfo) {\n queryInfo = new QueryListenersInfo();\n listenerAction = listener.listensToRemoteStore()\n ? ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection\n : ListenerSetupAction.InitializeLocalListenOnly;\n } else if (\n !queryInfo.hasRemoteListeners() &&\n listener.listensToRemoteStore()\n ) {\n // Query has been listening to local cache, and tries to add a new listener sourced from watch.\n listenerAction = ListenerSetupAction.RequireWatchConnectionOnly;\n }\n\n try {\n switch (listenerAction) {\n case ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection:\n queryInfo.viewSnap = await eventManagerImpl.onListen!(\n query,\n /** enableRemoteListen= */ true\n );\n break;\n case ListenerSetupAction.InitializeLocalListenOnly:\n queryInfo.viewSnap = await eventManagerImpl.onListen!(\n query,\n /** enableRemoteListen= */ false\n );\n break;\n case ListenerSetupAction.RequireWatchConnectionOnly:\n await eventManagerImpl.onFirstRemoteStoreListen!(query);\n break;\n default:\n break;\n }\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 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 {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n validateEventManager(eventManagerImpl);\n\n const query = listener.query;\n let listenerAction = ListenerRemovalAction.NoActionRequired;\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\n if (queryInfo.listeners.length === 0) {\n listenerAction = listener.listensToRemoteStore()\n ? ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection\n : ListenerRemovalAction.TerminateLocalListenOnly;\n } else if (\n !queryInfo.hasRemoteListeners() &&\n listener.listensToRemoteStore()\n ) {\n // The removed listener is the last one that sourced from watch.\n listenerAction = ListenerRemovalAction.RequireWatchDisconnectionOnly;\n }\n }\n }\n switch (listenerAction) {\n case ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection:\n eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten!(\n query,\n /** disableRemoteListen= */ true\n );\n case ListenerRemovalAction.TerminateLocalListenOnly:\n eventManagerImpl.queries.delete(query);\n return eventManagerImpl.onUnlisten!(\n query,\n /** disableRemoteListen= */ false\n );\n case ListenerRemovalAction.RequireWatchDisconnectionOnly:\n return eventManagerImpl.onLastRemoteStoreUnlisten!(query);\n default:\n return;\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\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\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n eventManagerImpl.snapshotsInSyncListeners.delete(observer);\n}\n\nfunction errorAllTargets(\n eventManager: EventManager,\n error: FirestoreError\n): void {\n const eventManagerImpl = debugCast(eventManager, EventManagerImpl);\n const queries = eventManagerImpl.queries;\n\n // Prevent further access by clearing ObjectMap.\n eventManagerImpl.queries = newQueriesObjectMap();\n\n queries.forEach((_, queryInfo) => {\n for (const listener of queryInfo.listeners) {\n listener.onError(error);\n }\n });\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 enum ListenerDataSource {\n /** Listen to both cache and server changes */\n Default = 'default',\n\n /** Listen to changes in cache only */\n Cache = 'cache'\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 /** Set the source events raised from. */\n readonly source?: ListenerDataSource;\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,\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 // Always raise event if listening to cache\n if (!this.listensToRemoteStore()) {\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 listensToRemoteStore(): boolean {\n return this.options.source !== ListenerDataSource.Cache;\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;\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(\n q => canonifyQuery(q),\n queryEquals\n );\n queriesByTarget = new Map();\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();\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(\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();\n limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n mutationUserCallbacks = {} as {\n [uidKey: string]: SortedMap>;\n };\n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n pendingWritesCallbacks = new Map>>();\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 shouldListenToRemote: boolean = true\n): Promise {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n\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 syncEngineImpl.sharedClientState.addLocalQueryTarget(queryView.targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n } else {\n viewSnapshot = await allocateTargetAndMaybeListen(\n syncEngineImpl,\n query,\n shouldListenToRemote,\n /** shouldInitializeView= */ true\n );\n debugAssert(!!viewSnapshot, 'viewSnapshot is not initialized');\n }\n\n return viewSnapshot;\n}\n\n/** Query has been listening to the cache, and tries to initiate the remote store listen */\nexport async function triggerRemoteStoreListen(\n syncEngine: SyncEngine,\n query: Query\n): Promise {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n await allocateTargetAndMaybeListen(\n syncEngineImpl,\n query,\n /** shouldListenToRemote= */ true,\n /** shouldInitializeView= */ false\n );\n}\n\nasync function allocateTargetAndMaybeListen(\n syncEngineImpl: SyncEngineImpl,\n query: Query,\n shouldListenToRemote: boolean,\n shouldInitializeView: boolean\n): Promise {\n const targetData = await localStoreAllocateTarget(\n syncEngineImpl.localStore,\n queryToTarget(query)\n );\n\n const targetId = targetData.targetId;\n\n // PORTING NOTE: When the query is listening to cache only, we skip sending it over to Watch by\n // not registering it in shared client state, and directly calculate initial snapshots and\n // subsequent updates from cache. Otherwise, register the target ID with local Firestore client\n // as active watch target.\n const status: QueryTargetState =\n syncEngineImpl.sharedClientState.addLocalQueryTarget(\n targetId,\n /* addToActiveTargetIds= */ shouldListenToRemote\n );\n\n let viewSnapshot;\n if (shouldInitializeView) {\n viewSnapshot = await initializeViewAndComputeSnapshot(\n syncEngineImpl,\n query,\n targetId,\n status === 'current',\n targetData.resumeToken\n );\n }\n\n if (syncEngineImpl.isPrimaryClient && shouldListenToRemote) {\n remoteStoreListen(syncEngineImpl.remoteStore, targetData);\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 {\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 shouldUnlistenToRemote: boolean\n): Promise {\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 if (shouldUnlistenToRemote) {\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\n }\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/** Unlistens to the remote store while still listening to the cache. */\nexport async function triggerRemoteStoreUnlisten(\n syncEngine: SyncEngine,\n query: Query\n): Promise {\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 const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId)!;\n\n if (syncEngineImpl.isPrimaryClient && queries.length === 1) {\n // PORTING NOTE: Unregister the target ID with local Firestore client as\n // watch target.\n syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n\n remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId);\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\n): Promise {\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 {\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 {\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(\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(),\n /* targetMismatches= */ new SortedMap(\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 {\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 {\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\n): Promise {\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\n): void {\n let newCallbacks =\n syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap>(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 {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n return syncEngineImpl.activeLimboTargetsByKey;\n}\n\n// Visible for testing\nexport function syncEngineGetEnqueuedLimboDocumentResolutions(\n syncEngine: SyncEngine\n): Set {\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 {\n const syncEngineImpl = debugCast(syncEngine, SyncEngineImpl);\n const newSnaps: ViewSnapshot[] = [];\n const docChangesInAllViews: LocalViewChanges[] = [];\n const queriesProcessed: Array> = [];\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 // Query state is set to `current` if:\n // - There is a view change and it is up-to-date, or,\n // - There is a global snapshot, the Target is current, and no changes to be resolved\n const isCurrent = viewSnapshot\n ? !viewSnapshot.fromCache\n : remoteEvent?.targetChanges.get(queryView.targetId)?.current;\n\n syncEngineImpl.sharedClientState.updateQueryState(\n queryView.targetId,\n isCurrent ? 'current' : 'not-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 {\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 {\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 {\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 {\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 {\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 {\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(\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 {\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 {\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 {\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 {\n const syncEngineImpl = ensureWatchCallbacks(syncEngine);\n if (!syncEngineImpl._isPrimaryClient) {\n return;\n }\n\n for (const targetId of added) {\n // A target is already listening to remote store if it is already registered to\n // sharedClientState.\n const targetAlreadyListeningToRemoteStore =\n syncEngineImpl.queriesByTarget.has(targetId) &&\n syncEngineImpl.sharedClientState.isActiveQueryTarget(targetId);\n if (targetAlreadyListeningToRemoteStore) {\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> {\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());\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());\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\ntype Kind = 'memory' | 'persistent';\n\nexport interface ComponentConfiguration {\n asyncQueue: AsyncQueue;\n databaseInfo: DatabaseInfo;\n authCredentials: CredentialsProvider;\n appCheckCredentials: CredentialsProvider;\n clientId: ClientId;\n initialUser: User;\n maxConcurrentLimboResolutions: number;\n}\n\nexport interface OfflineComponentProviderFactory {\n build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider;\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 readonly kind: Kind;\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;\n\n terminate(): Promise;\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 kind: Kind = 'memory';\n\n static readonly provider: OfflineComponentProviderFactory = {\n build: () => new MemoryOfflineComponentProvider()\n };\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 {\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 {\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 kind: Kind = 'persistent';\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 {\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 {\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\nexport interface OnlineComponentProviderFactory {\n build(): OnlineComponentProvider;\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */\nexport class OnlineComponentProvider {\n static readonly provider: OnlineComponentProviderFactory = {\n build: () => new OnlineComponentProvider()\n };\n\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 {\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 {\n await remoteStoreShutdown(this.remoteStore);\n this.datastore?.terminate();\n this.eventManager?.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 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 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 implements Observer {\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>) {}\n\n next(value: T): void {\n if (this.muted) {\n return;\n }\n if (this.observer.next) {\n this.scheduleEvent(this.observer.next, value);\n }\n }\n\n error(error: FirestoreError): void {\n if (this.muted) {\n return;\n }\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(eventHandler: EventHandler, event: E): void {\n setTimeout(() => {\n if (!this.muted) {\n eventHandler(event);\n }\n }, 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 { 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 triggerRemoteStoreListen,\n triggerRemoteStoreUnlisten\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 = () =>\n Promise.resolve();\n private appCheckCredentialListener: (\n appCheckToken: string,\n user: User\n ) => Promise = () => Promise.resolve();\n _uninitializedComponentsProvider?: {\n _offline: OfflineComponentProvider;\n _online: OnlineComponentProvider;\n };\n\n _offlineComponents?: OfflineComponentProvider;\n _onlineComponents?: OnlineComponentProvider;\n\n constructor(\n private authCredentials: CredentialsProvider,\n private appCheckCredentials: CredentialsProvider,\n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n public asyncQueue: AsyncQueue,\n private databaseInfo: DatabaseInfo,\n componentProvider?: {\n _offline: OfflineComponentProvider;\n _online: OnlineComponentProvider;\n }\n ) {\n this._uninitializedComponentsProvider = componentProvider;\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 {\n this.authCredentialListener = listener;\n }\n\n setAppCheckTokenChangeListener(\n listener: (appCheckToken: string, user: User) => Promise\n ): void {\n this.appCheckCredentialListener = listener;\n }\n\n terminate(): Promise {\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 {\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 {\n client.asyncQueue.verifyOperationInProgress();\n\n const offlineComponents = await ensureOfflineComponents(client);\n\n logDebug(LOG_TAG, 'Initializing OnlineComponentProvider');\n await onlineComponentProvider.initialize(\n offlineComponents,\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 {\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 {\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 {\n return ensureOfflineComponents(client).then(c => c.persistence);\n}\n\nexport function getLocalStore(client: FirestoreClient): Promise {\n return ensureOfflineComponents(client).then(c => c.localStore);\n}\n\nfunction getRemoteStore(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.remoteStore);\n}\n\nexport function getSyncEngine(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.syncEngine);\n}\n\nfunction getDatastore(client: FirestoreClient): Promise {\n return ensureOnlineComponents(client).then(c => c.datastore);\n}\n\nexport async function getEventManager(\n client: FirestoreClient\n): Promise {\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 eventManager.onFirstRemoteStoreListen = triggerRemoteStoreListen.bind(\n null,\n onlineComponentProvider.syncEngine\n );\n eventManager.onLastRemoteStoreUnlisten = triggerRemoteStoreUnlisten.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 {\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 {\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 {\n const deferred = new Deferred();\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>\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 {\n const deferred = new Deferred();\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 {\n const deferred = new Deferred();\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 {\n const deferred = new Deferred();\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 {\n const deferred = new Deferred();\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> {\n const deferred = new Deferred>();\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 {\n const deferred = new Deferred();\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>\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(\n client: FirestoreClient,\n updateFunction: (transaction: Transaction) => Promise,\n options: TransactionOptions\n): Promise {\n const deferred = new Deferred();\n client.asyncQueue.enqueueAndForget(async () => {\n const datastore = await getDatastore(client);\n new TransactionRunner(\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\n): Promise {\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\n): Promise {\n const wrappedObserver = new AsyncObserver({\n next: (snap: ViewSnapshot) => {\n // Mute and remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n wrappedObserver.mute();\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\n): Promise {\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\n): Promise {\n const wrappedObserver = new AsyncObserver({\n next: snapshot => {\n // Mute and remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n wrappedObserver.mute();\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 | 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 {\n return client.asyncQueue.enqueue(async () =>\n localStoreGetNamedQuery(await getLocalStore(client), queryName)\n );\n}\n\nfunction createBundleReader(\n data: ReadableStream | ArrayBuffer | string,\n serializer: JsonProtoSerializer\n): BundleReader {\n let content: ReadableStream | 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 {\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 {\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 {\n return client.asyncQueue.enqueue(async () => {\n return localStoreDeleteAllFieldIndexes(await getLocalStore(client));\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 SDK’s 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;\n _appCheckCredentials: CredentialsProvider;\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();\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(\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\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 = new SortedSet(\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 | 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 {\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 {\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 {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\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 {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\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({\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\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. Otherwise, Firestore is not terminated,\n // which can mean either the FirestoreClient is in the process of starting,\n // or restarting.\n private _terminateTask: Promise | 'notTerminated' = 'notTerminated';\n\n /** @hideconstructor */\n constructor(\n public _authCredentials: CredentialsProvider,\n public _appCheckCredentials: CredentialsProvider,\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 !== 'notTerminated';\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 {\n // The `_terminateTask` must be assigned future that completes when\n // terminate is complete. The existence of this future puts SDK in state\n // that will not accept further API interaction.\n if (this._terminateTask === 'notTerminated') {\n this._terminateTask = this._terminate();\n }\n return this._terminateTask;\n }\n\n async _restart(): Promise {\n // The `_terminateTask` must equal 'notTerminated' after restart to\n // signal that client is in a state that accepts API calls.\n if (this._terminateTask === 'notTerminated') {\n await this._terminate();\n } else {\n this._terminateTask = 'notTerminated';\n }\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 {\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 {\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`, but allows nested fields to be\n * omitted and FieldValues to be passed in as property values.\n */\nexport type PartialWithFieldValue =\n | Partial\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: PartialWithFieldValue | 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 =\n | T\n | (T extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]: WithFieldValue | 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 extends Primitive\n ? T\n : T extends {}\n ? { [K in keyof T]?: UpdateData | FieldValue } & NestedUpdateFields\n : Partial;\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;\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` that does not use a\n * converter.\n */\n withConverter(converter: null): Query;\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\n ): Query;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): Query {\n return new Query(\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 {\n return new CollectionReference(\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\n ): DocumentReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `DocumentReference` that does not\n * use a converter.\n */\n withConverter(converter: null): DocumentReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): DocumentReference {\n return new DocumentReference(\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 {\n /** The type of this Firestore reference. */\n readonly type = 'collection';\n\n /** @hideconstructor */\n constructor(\n firestore: Firestore,\n converter: FirestoreDataConverter | 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 | 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\n ): CollectionReference;\n /**\n * Removes the current converter.\n *\n * @param converter - `null` removes the current converter.\n * @returns A `CollectionReference` that does not\n * use a converter.\n */\n withConverter(\n converter: null\n ): CollectionReference;\n withConverter<\n NewAppModelType,\n NewDbModelType extends DocumentData = DocumentData\n >(\n converter: FirestoreDataConverter | null\n ): CollectionReference {\n return new CollectionReference(\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;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\n * `reference` at 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(\n reference: CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\n/**\n * Gets a `CollectionReference` instance that refers to a subcollection of\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 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(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference;\nexport function collection(\n parent:\n | Firestore\n | DocumentReference\n | CollectionReference,\n path: string,\n ...pathSegments: string[]\n): CollectionReference {\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 {\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;\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-generated 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(\n reference: CollectionReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference;\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(\n reference: DocumentReference,\n path: string,\n ...pathSegments: string[]\n): DocumentReference;\nexport function doc(\n parent:\n | Firestore\n | CollectionReference\n | DocumentReference,\n path?: string,\n ...pathSegments: string[]\n): DocumentReference {\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(\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(\n left:\n | DocumentReference\n | CollectionReference,\n right:\n | DocumentReference\n | CollectionReference\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(\n left: Query,\n right: Query\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;\n\n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n private retryableOps: Array<() => Promise> = [];\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> = [];\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(tail: Promise = Promise.resolve()) {\n this.tail = tail;\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(op: () => Promise): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n enqueueAndForgetEvenWhileRestricted(\n op: () => Promise\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(op: () => Promise): Promise {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise(() => {});\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();\n return this.enqueueInternal(() => {\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 {\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 {\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(op: () => Promise): Promise {\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(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise\n ): DelayedOperation {\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 overridden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation);\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 {\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;\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 {\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 /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\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): 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 /* eslint-disable-next-line @typescript-eslint/no-floating-promises */\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 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 OfflineComponentProviderFactory,\n OnlineComponentProvider,\n OnlineComponentProviderFactory\n} from '../core/component_provider';\nimport { DatabaseId, DEFAULT_DATABASE_NAME } from '../core/database_info';\nimport {\n FirestoreClient,\n firestoreClientDisableNetwork,\n firestoreClientEnableNetwork,\n firestoreClientGetNamedQuery,\n firestoreClientLoadBundle,\n firestoreClientWaitForPendingWrites\n} from '../core/firestore_client';\nimport { makeDatabaseInfo } from '../lite-api/components';\nimport {\n connectFirestoreEmulator,\n Firestore as LiteFirestore\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 { AsyncQueueImpl } 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 { FirestoreSettings, PersistenceSettings } from './settings';\n\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 _queue: AsyncQueue = new AsyncQueueImpl();\n readonly _persistenceKey: string;\n\n _firestoreClient: FirestoreClient | undefined;\n\n _componentsProvider?: {\n _offline: OfflineComponentProviderFactory;\n _online: OnlineComponentProviderFactory;\n };\n\n /** @hideconstructor */\n constructor(\n authCredentialsProvider: CredentialsProvider,\n appCheckCredentialsProvider: CredentialsProvider,\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 protected async _terminate(): Promise {\n if (this._firestoreClient) {\n const terminate = this._firestoreClient.terminate();\n this._queue = new AsyncQueueImpl(terminate);\n this._firestoreClient = undefined;\n await terminate;\n }\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._terminated) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n if (!firestore._firestoreClient) {\n configureFirestore(firestore);\n }\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 if (!firestore._componentsProvider) {\n if (\n settings.localCache?._offlineComponentProvider &&\n settings.localCache?._onlineComponentProvider\n ) {\n firestore._componentsProvider = {\n _offline: settings.localCache._offlineComponentProvider,\n _online: settings.localCache._onlineComponentProvider\n };\n }\n }\n firestore._firestoreClient = new FirestoreClient(\n firestore._authCredentials,\n firestore._appCheckCredentials,\n firestore._queue,\n databaseInfo,\n firestore._componentsProvider &&\n buildComponentProvider(firestore._componentsProvider)\n );\n}\n\nfunction buildComponentProvider(componentsProvider: {\n _offline: OfflineComponentProviderFactory;\n _online: OnlineComponentProviderFactory;\n}): {\n _offline: OfflineComponentProvider;\n _online: OnlineComponentProvider;\n} {\n const online = componentsProvider?._online.build();\n return {\n _offline: componentsProvider?._offline.build(online),\n _online: online\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 {\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 setPersistenceProviders(firestore, OnlineComponentProvider.provider, {\n build: (onlineComponents: OnlineComponentProvider) =>\n new IndexedDbOfflineComponentProvider(\n onlineComponents,\n settings.cacheSizeBytes,\n persistenceSettings?.forceOwnership\n )\n });\n return Promise.resolve();\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 async function enableMultiTabIndexedDbPersistence(\n firestore: Firestore\n): Promise {\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 setPersistenceProviders(firestore, OnlineComponentProvider.provider, {\n build: (onlineComponents: OnlineComponentProvider) =>\n new MultiTabOfflineComponentProvider(\n onlineComponents,\n settings.cacheSizeBytes\n )\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 firestore: Firestore,\n onlineComponentProvider: OnlineComponentProviderFactory,\n offlineComponentProvider: OfflineComponentProviderFactory\n): void {\n firestore = cast(firestore, Firestore);\n if (firestore._firestoreClient || 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 if (firestore._componentsProvider || firestore._getSettings().localCache) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'SDK cache is already specified.'\n );\n }\n\n firestore._componentsProvider = {\n _online: onlineComponentProvider,\n _offline: offlineComponentProvider\n };\n\n configureFirestore(firestore);\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 {\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();\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 {\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 {\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 {\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 {\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` 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`.\n */\nexport function loadBundle(\n firestore: Firestore,\n bundleData: ReadableStream | 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 {\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","/**\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 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPrimitiveArrayEqual } from '../util/array';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link FieldValue.vector}.\n *\n * @class VectorValue\n */\nexport class VectorValue {\n private readonly _values: number[];\n\n /**\n * @private\n * @internal\n */\n constructor(values: number[] | undefined) {\n // Making a copy of the parameter.\n this._values = (values || []).map(n => n);\n }\n\n /**\n * Returns a copy of the raw number array form of the vector.\n */\n toArray(): number[] {\n return this._values.map(n => n);\n }\n\n /**\n * Returns `true` if the two VectorValue has the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._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\n/**\n * Returns true iff the array contains the value using strong equality.\n */\nexport function includes(array: T[], value: T): boolean {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === value) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true iff the array contains any value matching the predicate\n */\nexport function some(array: T[], predicate: (t: T) => boolean): boolean {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls predicate function for each item in the array until the predicate\n * returns true, at which point the index of that item is returned. If the\n * predicate does not return true for any item, null is returned.\n */\nexport function findIndex(\n array: A[],\n predicate: (value: A) => boolean\n): number | null {\n for (let i = 0; i < array.length; i++) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return null;\n}\n\n/**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * 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 array.\n * @param after - The elements to diff against the original array.\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 diffArrays(\n before: T[],\n after: T[],\n comparator: (l: T, r: T) => number,\n onAdd: (entry: T) => void,\n onRemove: (entry: T) => void\n): void {\n before = [...before];\n after = [...after];\n before.sort(comparator);\n after.sort(comparator);\n\n const bLen = before.length;\n const aLen = after.length;\n let a = 0;\n let b = 0;\n while (a < aLen && b < bLen) {\n const cmp = comparator(before[b], after[a]);\n if (cmp < 0) {\n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n onRemove(before[b++]);\n } else if (cmp > 0) {\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n onAdd(after[a++]);\n } else {\n a++;\n b++;\n }\n }\n while (a < aLen) {\n onAdd(after[a++]);\n }\n while (b < bLen) {\n onRemove(before[b++]);\n }\n}\n\n/**\n * Verifies equality for an array of objects using the `isEqual` interface.\n *\n * @private\n * @internal\n * @param left Array of objects supporting `isEqual`.\n * @param right Array of objects supporting `isEqual`.\n * @return True if arrays are equal.\n */\nexport function isArrayEqual boolean }>(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Verifies equality for an array of primitives.\n *\n * @private\n * @internal\n * @param left Array of primitives.\n * @param right Array of primitives.\n * @return True if arrays are equal.\n */\nexport function isPrimitiveArrayEqual(\n left: T[],\n right: T[]\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; ++i) {\n if (left[i] !== right[i]) {\n return false;\n }\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 {\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 {\n TYPE_KEY,\n VECTOR_MAP_VECTORS_KEY,\n VECTOR_VALUE_SENTINEL\n} from '../model/values';\nimport { newSerializer } from '../platform/serializer';\nimport {\n MapValue as ProtoMapValue,\n Value as ProtoValue\n} from '../protos/firestore_proto_api';\nimport { toDouble, 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';\nimport { VectorValue } from './vector_value';\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\n ): WithFieldValue;\n toFirestore(\n modelObject: PartialWithFieldValue,\n options: SetOptions\n ): PartialWithFieldValue;\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): 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, (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,\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,\n context: ParseContextImpl\n): { mapValue: ProtoMapValue } {\n const fields: Dict = {};\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 if (value instanceof VectorValue) {\n return parseVectorValue(value, context);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n}\n\n/**\n * Creates a new VectorValue proto value (using the internal format).\n */\nexport function parseVectorValue(\n value: VectorValue,\n context: ParseContextImpl\n): ProtoValue {\n const mapValue: ProtoMapValue = {\n fields: {\n [TYPE_KEY]: {\n stringValue: VECTOR_VALUE_SENTINEL\n },\n [VECTOR_MAP_VECTORS_KEY]: {\n arrayValue: {\n values: value.toArray().map(value => {\n if (typeof value !== 'number') {\n throw context.createError(\n 'VectorValues must only contain numeric values.'\n );\n }\n\n return toDouble(context.serializer, value);\n })\n }\n }\n }\n };\n\n return { mapValue };\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 !(input instanceof VectorValue)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContextImpl,\n input: unknown\n): asserts input is Dict {\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,\n targetDoc?: DocumentKey\n): InternalFieldPath {\n // If required, replace the FieldPath Compat class 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) {\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 {\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 {\n * toFirestore(post: WithFieldValue): WithFieldValue {\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 {\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` 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`. 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\"\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 = 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` 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`.\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\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = 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` 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\n ): WithFieldValue;\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` type extends `Partial` 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,\n options: SetOptions\n ): PartialWithFieldValue;\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\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()` 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 {\n return new DocumentReference(\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 {\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()` 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 {\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;\n\n /** @hideconstructor */\n constructor(\n _query: Query,\n readonly _docs: Array>\n ) {\n this.query = _query;\n }\n\n /** An array of all the documents in the `QuerySnapshot`. */\n get docs(): Array> {\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\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(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\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\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(\n query: Query\n ): Query;\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(\n query: Query\n ): Query;\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(\n query: Query,\n compositeFilter: QueryCompositeFilterConstraint,\n ...queryConstraints: QueryNonFilterConstraint[]\n): Query;\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(\n query: Query,\n ...queryConstraints: QueryConstraint[]\n): Query;\n\nexport function query(\n query: Query,\n queryConstraint: QueryCompositeFilterConstraint | QueryConstraint | undefined,\n ...additionalQueryConstraints: Array<\n QueryConstraint | QueryNonFilterConstraint\n >\n): Query {\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(\n query: Query\n ): Query {\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(\n query: Query\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 '<', '<=', '==', '!=', '>=', '>', '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 \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\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(\n query: Query\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(\n query: Query\n ): Query {\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(\n query: Query\n ): Query {\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(\n query: Query\n ): Query {\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>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'startAt' | 'startAfter',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryStartAtConstraint {\n return new QueryStartAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\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 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(\n snapshot: DocumentSnapshot\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(\n ...docOrFields: Array>\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(\n snapshot: DocumentSnapshot\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(\n ...docOrFields: Array>\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>,\n private readonly _inclusive: boolean\n ) {\n super();\n }\n\n static _create(\n type: 'endBefore' | 'endAt',\n _docOrFields: Array>,\n _inclusive: boolean\n ): QueryEndAtConstraint {\n return new QueryEndAtConstraint(type, _docOrFields, _inclusive);\n }\n\n _apply(\n query: Query\n ): Query {\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(\n snapshot: DocumentSnapshot\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(\n ...docOrFields: Array>\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(\n snapshot: DocumentSnapshot\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(\n ...docOrFields: Array>\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,\n methodName: string,\n docOrFields: Array>,\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 { VECTOR_MAP_VECTORS_KEY, 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';\nimport { VectorValue } from './vector_value';\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 case TypeOrder.VectorValue:\n return this.convertVectorValue(value.mapValue!);\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 | 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 /**\n * @internal\n */\n convertVectorValue(mapValue: ProtoMapValue): VectorValue {\n const values = mapValue.fields?.[\n VECTOR_MAP_VECTORS_KEY\n ].arrayValue?.values?.map(value => {\n return normalizeNumber(value.doubleValue);\n });\n\n return new VectorValue(values);\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 { 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) {\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 {\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 {\n * toFirestore(post: WithFieldValue): WithFieldValue {\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 {\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` 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`. 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\"\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 = 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` 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`.\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\"\n * await updateDoc(documentRef, { title: 'New Title' });\n * const snapshot2: DocumentSnapshot = 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 {\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`.\n *\n * The `WithFieldValue` 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\n ): WithFieldValue;\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` type extends `Partial` 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,\n options: SetOptions\n ): PartialWithFieldValue;\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,\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;\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()` 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 {\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 | 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 {\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()` 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 {\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;\n\n private _cachedChanges?: Array>;\n private _cachedChangesIncludeMetadataChanges?: boolean;\n\n /** @hideconstructor */\n constructor(\n readonly _firestore: Firestore,\n readonly _userDataWriter: AbstractUserDataWriter,\n query: Query,\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> {\n const result: Array> = [];\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\n ) => void,\n thisArg?: unknown\n ): void {\n this._snapshot.docs.forEach(doc => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot(\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> {\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,\n includeMetadataChanges: boolean\n): Array> {\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(\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(\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(\n left:\n | DocumentSnapshot\n | QuerySnapshot,\n right:\n | DocumentSnapshot\n | QuerySnapshot\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 { ListenerDataSource } from '../core/event_manager';\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 * Set the source the query listens to. Default to \"default\", which\n * listens to both cache and server.\n */\n readonly source?: ListenSource;\n}\n\n/**\n * Describe the source a query listens to.\n *\n * Set to `default` to listen to both cache and server changes. Set to `cache`\n * to listen to changes in cache only.\n */\nexport type ListenSource = 'default' | 'cache';\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(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\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(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\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(\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\n): Promise> {\n reference = cast>(\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(\n query: Query\n): Promise> {\n query = cast>(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(\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\n): Promise> {\n query = cast>(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(\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\n): Promise> {\n query = cast>(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(\n reference: DocumentReference,\n data: WithFieldValue\n): Promise;\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(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n): Promise;\nexport function setDoc(\n reference: DocumentReference,\n data: PartialWithFieldValue,\n options?: SetOptions\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const firestore = cast(reference.firestore, Firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as WithFieldValue,\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(\n reference: DocumentReference,\n data: UpdateData\n): Promise;\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(\n reference: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise;\nexport function updateDoc(\n reference: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n): Promise {\n reference = cast>(\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(\n reference: DocumentReference\n): Promise {\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(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\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(\n reference: DocumentReference,\n observer: {\n next?: (snapshot: DocumentSnapshot) => 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(\n reference: DocumentReference,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: DocumentSnapshot) => 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(\n reference: DocumentReference,\n onNext: (snapshot: DocumentSnapshot) => 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(\n reference: DocumentReference,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot) => 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(\n query: Query,\n observer: {\n next?: (snapshot: QuerySnapshot) => 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(\n query: Query,\n options: SnapshotListenOptions,\n observer: {\n next?: (snapshot: QuerySnapshot) => 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(\n query: Query,\n onNext: (snapshot: QuerySnapshot) => 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(\n query: Query,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void\n): Unsubscribe;\nexport function onSnapshot(\n reference:\n | Query\n | DocumentReference,\n ...args: unknown[]\n): Unsubscribe {\n reference = getModularInstance(reference);\n\n let options: SnapshotListenOptions = {\n includeMetadataChanges: false,\n source: 'default'\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 source: options.source as ListenerDataSource\n };\n\n if (isPartialObserver(args[currArg])) {\n const userObserver = args[currArg] as PartialObserver<\n QuerySnapshot\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;\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>\n )(\n convertToDocSnapshot(\n firestore,\n reference as DocumentReference,\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>(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>)(\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)\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 {\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(\n firestore: Firestore,\n ref: DocumentReference,\n snapshot: ViewSnapshot\n): DocumentSnapshot {\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(\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 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 firestoreClientDeleteAllFieldIndexes,\n firestoreClientSetPersistentCacheIndexAutoCreationEnabled\n} from '../core/firestore_client';\nimport { cast } from '../util/input_validation';\nimport { logDebug, logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\n/**\n * A `PersistentCacheIndexManager` for configuring persistent cache indexes used\n * for local query execution.\n *\n * To use, call `getPersistentCacheIndexManager()` to get an instance.\n */\nexport class PersistentCacheIndexManager {\n /** A type string to uniquely identify instances of this class. */\n readonly type: 'PersistentCacheIndexManager' = 'PersistentCacheIndexManager';\n\n /** @hideconstructor */\n constructor(readonly _firestore: Firestore) {}\n}\n\n/**\n * Returns the PersistentCache Index Manager used by the given `Firestore`\n * object.\n *\n * @return The `PersistentCacheIndexManager` instance, or `null` if local\n * persistent storage is not in use.\n */\nexport function getPersistentCacheIndexManager(\n firestore: Firestore\n): PersistentCacheIndexManager | null {\n firestore = cast(firestore, Firestore);\n\n const cachedInstance = persistentCacheIndexManagerByFirestore.get(firestore);\n if (cachedInstance) {\n return cachedInstance;\n }\n\n const client = ensureFirestoreConfigured(firestore);\n if (client._uninitializedComponentsProvider?._offline.kind !== 'persistent') {\n return null;\n }\n\n const instance = new PersistentCacheIndexManager(firestore);\n persistentCacheIndexManagerByFirestore.set(firestore, instance);\n return instance;\n}\n\n/**\n * Enables the SDK to create persistent cache indexes automatically for local\n * query execution when the SDK believes cache indexes can help improve\n * performance.\n *\n * This feature is disabled by default.\n */\nexport function enablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, true);\n}\n\n/**\n * Stops creating persistent cache indexes automatically for local query\n * execution. The indexes which have been created by calling\n * `enablePersistentCacheIndexAutoCreation()` still take effect.\n */\nexport function disablePersistentCacheIndexAutoCreation(\n indexManager: PersistentCacheIndexManager\n): void {\n setPersistentCacheIndexAutoCreationEnabled(indexManager, false);\n}\n\n/**\n * Removes all persistent cache indexes.\n *\n * Please note this function will also deletes indexes generated by\n * `setIndexConfiguration()`, which is deprecated.\n */\nexport function deleteAllPersistentCacheIndexes(\n indexManager: PersistentCacheIndexManager\n): void {\n const client = ensureFirestoreConfigured(indexManager._firestore);\n const promise = firestoreClientDeleteAllFieldIndexes(client);\n\n promise\n .then(_ => logDebug('deleting all persistent cache indexes succeeded'))\n .catch(error =>\n logWarn('deleting all persistent cache indexes failed', error)\n );\n}\n\nfunction setPersistentCacheIndexAutoCreationEnabled(\n indexManager: PersistentCacheIndexManager,\n isEnabled: boolean\n): void {\n const client = ensureFirestoreConfigured(indexManager._firestore);\n const promise = firestoreClientSetPersistentCacheIndexAutoCreationEnabled(\n client,\n isEnabled\n );\n\n promise\n .then(_ =>\n logDebug(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} succeeded`\n )\n )\n .catch(error =>\n logWarn(\n `setting persistent cache index auto creation ` +\n `isEnabled=${isEnabled} failed`,\n error\n )\n );\n}\n\n/**\n * Maps `Firestore` instances to their corresponding\n * `PersistentCacheIndexManager` instances.\n *\n * Use a `WeakMap` so that the mapping will be automatically dropped when the\n * `Firestore` instance is garbage collected. This emulates a private member\n * as described in https://goo.gle/454yvug.\n */\nconst persistentCacheIndexManagerByFirestore = new WeakMap<\n Firestore,\n PersistentCacheIndexManager\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 * Cloud Firestore\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 { Firestore } from './api/database';\nimport { registerFirestore } from './register';\n\nregisterFirestore();\n\nexport * from './api';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore': Firestore;\n }\n}\n","import PropTypes from 'prop-types';\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst propTypes = {\n /** An accessible label indicating the relevant information about the Close Button. */\n 'aria-label': PropTypes.string,\n /** A callback fired after the Close Button is clicked. */\n onClick: PropTypes.func,\n /**\n * Render different color variant for the button.\n *\n * Omitting this will render the default dark color.\n */\n variant: PropTypes.oneOf(['white'])\n};\nconst CloseButton = /*#__PURE__*/React.forwardRef(({\n className,\n variant,\n 'aria-label': ariaLabel = 'Close',\n ...props\n}, ref) => /*#__PURE__*/_jsx(\"button\", {\n ref: ref,\n type: \"button\",\n className: classNames('btn-close', variant && `btn-close-${variant}`, className),\n \"aria-label\": ariaLabel,\n ...props\n}));\nCloseButton.displayName = 'CloseButton';\nCloseButton.propTypes = propTypes;\nexport default CloseButton;","import css from 'dom-helpers/css';\nimport transitionEnd from 'dom-helpers/transitionEnd';\nfunction parseDuration(node, property) {\n const str = css(node, property) || '';\n const mult = str.indexOf('ms') === -1 ? 1000 : 1;\n return parseFloat(str) * mult;\n}\nexport default function transitionEndListener(element, handler) {\n const duration = parseDuration(element, 'transitionDuration');\n const delay = parseDuration(element, 'transitionDelay');\n const remove = transitionEnd(element, e => {\n if (e.target === element) {\n remove();\n handler(e);\n }\n }, duration + delay);\n}","import React, { useCallback, useRef } from 'react';\nimport Transition from 'react-transition-group/Transition';\nimport useMergedRefs from '@restart/hooks/useMergedRefs';\nimport safeFindDOMNode from './safeFindDOMNode';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\n// Normalizes Transition callbacks when nodeRef is used.\nconst TransitionWrapper = /*#__PURE__*/React.forwardRef(({\n onEnter,\n onEntering,\n onEntered,\n onExit,\n onExiting,\n onExited,\n addEndListener,\n children,\n childRef,\n ...props\n}, ref) => {\n const nodeRef = useRef(null);\n const mergedRef = useMergedRefs(nodeRef, childRef);\n const attachRef = r => {\n mergedRef(safeFindDOMNode(r));\n };\n const normalize = callback => param => {\n if (callback && nodeRef.current) {\n callback(nodeRef.current, param);\n }\n };\n\n /* eslint-disable react-hooks/exhaustive-deps */\n const handleEnter = useCallback(normalize(onEnter), [onEnter]);\n const handleEntering = useCallback(normalize(onEntering), [onEntering]);\n const handleEntered = useCallback(normalize(onEntered), [onEntered]);\n const handleExit = useCallback(normalize(onExit), [onExit]);\n const handleExiting = useCallback(normalize(onExiting), [onExiting]);\n const handleExited = useCallback(normalize(onExited), [onExited]);\n const handleAddEndListener = useCallback(normalize(addEndListener), [addEndListener]);\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return /*#__PURE__*/_jsx(Transition, {\n ref: ref,\n ...props,\n onEnter: handleEnter,\n onEntered: handleEntered,\n onEntering: handleEntering,\n onExit: handleExit,\n onExited: handleExited,\n onExiting: handleExiting,\n addEndListener: handleAddEndListener,\n nodeRef: nodeRef,\n children: typeof children === 'function' ? (status, innerProps) =>\n // TODO: Types for RTG missing innerProps, so need to cast.\n children(status, {\n ...innerProps,\n ref: attachRef\n }) : /*#__PURE__*/React.cloneElement(children, {\n ref: attachRef\n })\n });\n});\nexport default TransitionWrapper;","import ReactDOM from 'react-dom';\nexport default function safeFindDOMNode(componentOrElement) {\n if (componentOrElement && 'setState' in componentOrElement) {\n return ReactDOM.findDOMNode(componentOrElement);\n }\n return componentOrElement != null ? componentOrElement : null;\n}","import classNames from 'classnames';\nimport * as React from 'react';\nimport { useCallback } from 'react';\nimport { ENTERED, ENTERING } from 'react-transition-group/Transition';\nimport transitionEndListener from './transitionEndListener';\nimport triggerBrowserReflow from './triggerBrowserReflow';\nimport TransitionWrapper from './TransitionWrapper';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst fadeStyles = {\n [ENTERING]: 'show',\n [ENTERED]: 'show'\n};\nconst Fade = /*#__PURE__*/React.forwardRef(({\n className,\n children,\n transitionClasses = {},\n onEnter,\n ...rest\n}, ref) => {\n const props = {\n in: false,\n timeout: 300,\n mountOnEnter: false,\n unmountOnExit: false,\n appear: false,\n ...rest\n };\n const handleEnter = useCallback((node, isAppearing) => {\n triggerBrowserReflow(node);\n onEnter == null ? void 0 : onEnter(node, isAppearing);\n }, [onEnter]);\n return /*#__PURE__*/_jsx(TransitionWrapper, {\n ref: ref,\n addEndListener: transitionEndListener,\n ...props,\n onEnter: handleEnter,\n childRef: children.ref,\n children: (status, innerProps) => /*#__PURE__*/React.cloneElement(children, {\n ...innerProps,\n className: classNames('fade', className, children.props.className, fadeStyles[status], transitionClasses[status])\n })\n });\n});\nFade.displayName = 'Fade';\nexport default Fade;","// reading a dimension prop will cause the browser to recalculate,\n// which will let our animations work\nexport default function triggerBrowserReflow(node) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n node.offsetHeight;\n}","import { useEffect, useRef } from 'react';\n\n/**\n * Creates a `Ref` whose value is updated in an effect, ensuring the most recent\n * value is the one rendered with. Generally only required for Concurrent mode usage\n * where previous work in `render()` may be discarded before being used.\n *\n * This is safe to access in an event handler.\n *\n * @param value The `Ref` value\n */\nfunction useCommittedRef(value) {\n const ref = useRef(value);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n}\nexport default useCommittedRef;","import { useCallback } from 'react';\nimport useCommittedRef from './useCommittedRef';\nexport default function useEventCallback(fn) {\n const ref = useCommittedRef(fn);\n return useCallback(function (...args) {\n return ref.current && ref.current(...args);\n }, [ref]);\n}","import { useRef, useEffect } from 'react';\n\n/**\n * Track whether a component is current mounted. Generally less preferable than\n * properlly canceling effects so they don't run after a component is unmounted,\n * but helpful in cases where that isn't feasible, such as a `Promise` resolution.\n *\n * @returns a function that returns the current isMounted state of the component\n *\n * ```ts\n * const [data, setData] = useState(null)\n * const isMounted = useMounted()\n *\n * useEffect(() => {\n * fetchdata().then((newData) => {\n * if (isMounted()) {\n * setData(newData);\n * }\n * })\n * })\n * ```\n */\nexport default function useMounted() {\n const mounted = useRef(true);\n const isMounted = useRef(() => mounted.current);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n return isMounted.current;\n}","import { Card } from \"react-bootstrap\";\n\n// Button Component\nconst Button = ({ text, classes, onClick }) => (\n \n);\n\n// Footer Component\nconst Footer = ({ tries, remaining, selected, setSelected, handleSubmit, guessed, setShowResults }) => (\n \n {tries > 0 && remaining.length > 0 && (\n <>\n